diff --git a/.github/ISSUE_TEMPLATE/Bug_report.md b/.github/ISSUE_TEMPLATE/Bug_report.md index fe94434490c..6add1cccb58 100644 --- a/.github/ISSUE_TEMPLATE/Bug_report.md +++ b/.github/ISSUE_TEMPLATE/Bug_report.md @@ -16,7 +16,7 @@ Please fill in the *entire* template below. --> -**TypeScript Version:** 3.1.0-dev.201xxxxx +**TypeScript Version:** 3.2.0-dev.201xxxxx **Search Terms:** diff --git a/.travis.yml b/.travis.yml index 9479fffe763..6d000dd7165 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,6 +20,7 @@ branches: - release-2.8 - release-2.9 - release-3.0 + - release-3.1 install: - npm uninstall typescript --no-save diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000000..65c8a42b8d2 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1 @@ +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 81ffe06e8e2..c937316603f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,7 +72,7 @@ Your pull request should: * Requests need not be a single commit, but should be a linear sequence of commits (i.e. no merge commits in your PR) * It is desirable, but not necessary, for the tests to pass at each commit * Have clear commit messages - * e.g. "Refactor feature", "Fix issue", "Add tests for issue" + * e.g. "Minor refactor in goToTypeDefinition", "Fix iterated type in for-await-of", "Add test for preserveWatchOutput on command line" * Include adequate tests * At least one test should fail in the absence of your non-test code changes. If your PR does not match this criteria, please specify why * Tests should include reasonable permutations of the target fix/change @@ -104,7 +104,7 @@ To run all tests, invoke the `runtests-parallel` target using jake: jake runtests-parallel ``` -This run will all tests; to run only a specific subset of tests, use: +This will run all tests; to run only a specific subset of tests, use: ```Shell jake runtests tests= @@ -194,6 +194,6 @@ to establish the new baselines as the desired behavior. This will change the fil ## Localization All strings the user may see are stored in [`diagnosticMessages.json`](./src/compiler/diagnosticMessages.json). -If you make changes to it, run `jake generate-diagnostics` to push them to the `Diagnostic` interface in [`diagnosticInformationMap.generated.ts`](./src/compiler/diagnosticInformationMap.generated.ts). +If you make changes to it, run `jake generate-diagnostics` to push them to the `Diagnostic` interface in `diagnosticInformationMap.generated.ts`. See [coding guidelines on diagnostic messages](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#diagnostic-messages). diff --git a/README.md b/README.md index ede02510dca..a8b068bbab8 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Change to the TypeScript directory: cd TypeScript ``` -Install Jake tools and dev dependencies: +Install [Jake](http://jakejs.com/) tools and dev dependencies: ```bash npm install -g jake diff --git a/doc/spec.md b/doc/spec.md index ed99088443f..c6dd8cb4d06 100644 --- a/doc/spec.md +++ b/doc/spec.md @@ -286,7 +286,7 @@ function f(s) { } ``` -In the JavaScript output, all type annotations have been erased. In general, TypeScript erases all type information before emiting JavaScript. +In the JavaScript output, all type annotations have been erased. In general, TypeScript erases all type information before emitting JavaScript. ## 1.1 Ambient Declarations diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 795136609dc..f7bf53b6755 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -938,7 +938,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Der Typ iterierter Elemente eines \"yield*\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Der Typ eines \"yield\"-Operanden in einem asynchronen Generator muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_parameter_0_has_a_circular_constraint_2313": "Der Typparameter \"{0}\" weist eine zirkuläre Einschränkung auf.", - "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" weist einen zirkulären Standard auf.", + "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" besitzt einen zirkulären Standardwert.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Der Typparameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Der Typparameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Der Typparameter \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 2c93bcf114d..58166339abe 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -135,9 +135,9 @@ - + - + @@ -861,6 +861,18 @@ + + + + + + + + + + + + @@ -1233,6 +1245,12 @@ + + + + + + @@ -1401,6 +1419,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2001,6 +2049,18 @@ + + + + + + + + + + + + @@ -2259,6 +2319,12 @@ + + + + + + @@ -2349,6 +2415,12 @@ + + + + + + @@ -2421,9 +2493,9 @@ - + - + @@ -2781,6 +2853,18 @@ + + + + + + + + + + + + @@ -2829,12 +2913,6 @@ - - - - - - @@ -3225,6 +3303,12 @@ + + + + + + @@ -3255,6 +3339,12 @@ + + + + + + @@ -3705,6 +3795,12 @@ + + + + + + @@ -3909,9 +4005,9 @@ - + - + @@ -5025,12 +5121,6 @@ - - - - - - @@ -5313,6 +5403,12 @@ + + + + + + @@ -5589,6 +5685,12 @@ + + + + + + @@ -6051,6 +6153,12 @@ + + + + + + @@ -6207,6 +6315,12 @@ + + + + + + @@ -6393,6 +6507,12 @@ + + + + + + @@ -6657,12 +6777,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -6831,6 +6975,18 @@ + + + + + + + + + + + + diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 0e0e31a2b11..52840b1208e 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -328,7 +328,7 @@ "Do_not_emit_outputs_if_any_errors_were_reported_6008": "No emitir salidas si se informa de algún error.", "Do_not_emit_use_strict_directives_in_module_output_6112": "No emitir directivas 'use strict' en la salida del módulo.", "Do_not_erase_const_enum_declarations_in_generated_code_6007": "No borrar las declaraciones de enumeración const en el código generado.", - "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones auxiliares personalizadas como \"__extends\" en la salida compilada.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones del asistente personalizadas como \"__extends\" en la salida compilada.", "Do_not_include_the_default_library_file_lib_d_ts_6158": "No incluir el archivo de biblioteca predeterminado (lib.d.ts).", "Do_not_report_errors_on_unreachable_code_6077": "No notificar los errores del código inaccesible.", "Do_not_report_errors_on_unused_labels_6074": "No notificar los errores de las etiquetas no usadas.", @@ -477,7 +477,7 @@ "Import_declaration_0_is_using_private_name_1_4000": "La declaración de importación '{0}' usa el nombre privado '{1}'.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La declaración de importación está en conflicto con la declaración local de \"{0}\".", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Las declaraciones de importación de un espacio de nombres no pueden hacer referencia a un módulo.", - "Import_emit_helpers_from_tslib_6139": "Importe elementos auxiliares de emisión de \"tslib\".", + "Import_emit_helpers_from_tslib_6139": "Importe asistentes de emisión de \"tslib\".", "Import_may_be_converted_to_a_default_import_80003": "La importación puede convertirse a una importación predeterminada.", "Import_name_cannot_be_0_2438": "El nombre de importación no puede ser \"{0}\".", "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La declaración de importación o exportación de una declaración de módulo de ambiente no puede hacer referencia al módulo a través de su nombre relativo.", @@ -892,8 +892,8 @@ "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La declaración de variable de una instrucción \"for...of\" no puede tener un inicializador.", "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "No se admite la instrucción 'with'. Todos los símbolos de un bloque 'with' tendrán el tipo 'any'.", "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Esta función de constructor puede convertirse en una declaración de clase.", - "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere una aplicación auxiliar importada, pero no se puede encontrar el módulo \"{0}\".", - "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Esta sintaxis requiere una aplicación auxiliar importada denominada \"{1}\", pero el módulo \"{0}\" no tiene el miembro exportado \"{1}\".", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere un asistente importado, pero no se puede encontrar el módulo \"{0}\".", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Esta sintaxis requiere un asistente importado denominado \"{1}\", pero el módulo \"{0}\" no tiene el miembro exportado \"{1}\".", "Trailing_comma_not_allowed_1009": "No se permite la coma final.", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilar cada archivo como un módulo aparte (parecido a \"ts.transpileModule\").", "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Pruebe \"npm install @types/{0}\" si existe o agregue un nuevo archivo de declaración (.d.ts) que incluya \"declare module '{0}';\"", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index c5d6cf984db..1003d62329c 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -68,7 +68,7 @@ "A_rest_parameter_cannot_have_an_initializer_1048": "rest 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 매개 변수는 매개 변수 목록 마지막에 있어야 합니다.", "A_rest_parameter_must_be_of_an_array_type_2370": "rest 매개 변수는 배열 형식이어야 합니다.", - "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest 매개 변수 또는 바인딩 패턴에 후행 쉼표를 사용할 수 없습니다.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest 매개 변수 또는 바인딩 패턴에 후행 쉼표가 없을 수 있습니다.", "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' 문은 함수 본문 내에서만 사용할 수 있습니다.", "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "가져오기를 'baseUrl'에 상대적인 조회 위치로 다시 매핑하는 일련의 항목입니다.", "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' 접근자에는 반환 형식 주석을 사용할 수 없습니다.", @@ -232,7 +232,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": "'outFile' 집합이 없기 때문에 '{0}' 프로젝트를 추가할 수 없습니다.", + "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}'을(를) 다시 선언할 수 없습니다.", @@ -274,7 +274,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_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": "출력을 연결하고 단일 파일로 내보냅니다.", @@ -445,7 +445,7 @@ "Function_overload_must_be_static_2387": "함수 오버로드는 정적이어야 합니다.", "Function_overload_must_not_be_static_2388": "함수 오버로드는 정적이 아니어야 합니다.", "Generate_get_and_set_accessors_95046": "'get' 및 'set' 접근자 생성", - "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "해당하는 각 '.d.ts' 파일의 sourcemap을 생성합니다.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "해당하는 각 '.d.ts' 파일에 sourcemap을 생성합니다.", "Generates_corresponding_d_ts_file_6002": "해당 '.d.ts' 파일을 생성합니다.", "Generates_corresponding_map_file_6043": "해당 '.map' 파일을 생성합니다.", "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "생성기는 값을 생성하지 않으므로 암시적으로 '{0}' 형식입니다. 반환 형식을 제공하세요.", @@ -677,13 +677,13 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.", "Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.", "Print_this_message_6017": "이 메시지를 출력합니다.", - "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{1}' 종속성에 오류가 있기 때문에 '{0}' 프로젝트를 빌드할 수 없습니다.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{0}' 프로젝트는 '{1}' 종속성에 오류가 있기 때문에 빌드할 수 없습니다.", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "'{1}' 종속성이 최신 상태가 아니기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "가장 오래된 출력 '{1}'이(가) 최신 입력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "'{1}' 출력 파일이 존재하지 않기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_up_to_date_6361": "'{0}' 프로젝트가 최신 상태입니다.", "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "최신 입력 '{1}'이(가) 가장 오래된 출력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태입니다.", - "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "종속성의 .d.ts 파일이 있기 때문에 '{0}' 프로젝트가 최신 상태입니다.", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "'{0}' 프로젝트는 종속성에 .d.ts 파일이 있는 최신 상태입니다.", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "프로젝트 참조는 순환 그래프를 형성할 수 없습니다. 순환이 발견되었습니다. {0}", "Projects_in_this_build_Colon_0_6355": "이 빌드의 프로젝트: {0}", "Projects_to_reference_6300": "참조할 프로젝트", @@ -803,7 +803,7 @@ "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "빌드될 항목 표시(또는 '--clean'으로 지정된 경우 삭제될 항목 표시)", "Signature_0_must_be_a_type_predicate_1224": "'{0}' 시그니처는 형식 조건자여야 합니다.", "Skip_type_checking_of_declaration_files_6012": "선언 파일 형식 검사를 건너뜁니다.", - "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "'{1}' 종속성에 오류가 있기 때문에 '{0}' 프로젝트 빌드를 건너뜁니다.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "'{0}' 프로젝트의 빌드는 '{1}' 종속성에 오류가 있기 때문에 건너뜁니다.", "Skipping_clean_because_not_all_projects_could_be_located_6371": "일부 프로젝트를 찾을 수 없으므로 정리를 건너뛰는 중입니다.", "Source_Map_Options_6175": "소스 맵 옵션", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "특수화된 오버로드 시그니처는 특수화되지 않은 서명에 할당할 수 없습니다.", @@ -1039,7 +1039,7 @@ "const_declarations_must_be_initialized_1155": "'const' 선언은 초기화해야 합니다.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 열거형 멤버 이니셜라이저가 무한 값에 대해 평가되었습니다.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 열거형 멤버 이니셜라이저가 허용되지 않은 'NaN' 값에 대해 평가되었습니다.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성 또는 인덱스 액세스 식 또는 내보내기 할당 또는 가져오기 선언의 오른쪽 또는 형식 쿼리에서만 사용할 수 있습니다.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성이나 인덱스 액세스 식, 또는 내보내기 할당이나 가져오기 선언의 오른쪽, 또는 형식 쿼리에서만 사용할 수 있습니다.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "strict 모드에서는 식별자에 대해 'delete'를 호출할 수 없습니다.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "이 항목 삭제 - '{0}' 프로젝트는 이전에 빌드되었기 때문에 최신 상태입니다.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum 선언'은 .ts 파일에서만 사용할 수 있습니다.", diff --git a/lib/lib.es2015.promise.d.ts b/lib/lib.es2015.promise.d.ts index 9f27b7b59ab..002d69165fd 100644 --- a/lib/lib.es2015.promise.d.ts +++ b/lib/lib.es2015.promise.d.ts @@ -27,7 +27,7 @@ interface PromiseConstructor { /** * Creates a new Promise. * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, + * a resolve callback used to resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; @@ -213,4 +213,4 @@ interface PromiseConstructor { resolve(): Promise; } -declare var Promise: PromiseConstructor; \ No newline at end of file +declare var Promise: PromiseConstructor; diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 840fd682789..d1a9d6f0d2a 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -315,6 +315,66 @@ interface FunctionConstructor { declare const Function: FunctionConstructor; +interface CallableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: (this: T) => R, thisArg: T): R; + apply(this: (this: T, ...args: A) => R, thisArg: T, args: A): R; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: (this: T, ...args: A) => R, thisArg: T): (...args: A) => R; + bind(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R; + bind(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R; +} + +interface NewableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: new () => T, thisArg: T): void; + apply(this: new (...args: A) => T, thisArg: T, args: A): void; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: new (...args: A) => T, thisArg: T, ...args: A): void; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: new (...args: A) => R, thisArg: any): new (...args: A) => R; + bind(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2, arg3: A3): new (...args: A) => R; + bind(this: new (...args: AX[]) => R, thisArg: any, ...args: AX[]): new (...args: AX[]) => R; +} + interface IArguments { [index: number]: any; length: number; @@ -1370,7 +1430,7 @@ type Readonly = { }; /** - * From T pick a set of properties K + * From T, pick a set of properties whose keys are in the union K */ type Pick = { [P in K]: T[P]; @@ -1398,6 +1458,16 @@ type Extract = T extends U ? T : never; */ type NonNullable = T extends null | undefined ? never : T; +/** + * Obtain the parameters of a function type in a tuple + */ +type Parameters any> = T extends (...args: infer P) => any ? P : never; + +/** + * Obtain the parameters of a constructor function type in a tuple + */ +type ConstructorParameters any> = T extends new (...args: infer P) => any ? P : never; + /** * Obtain the return type of a function type */ diff --git a/lib/lib.esnext.array.d.ts b/lib/lib.esnext.array.d.ts index 3da8562d2ea..6c751223209 100644 --- a/lib/lib.esnext.array.d.ts +++ b/lib/lib.esnext.array.d.ts @@ -31,7 +31,7 @@ interface ReadonlyArray { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|U[], + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, thisArg?: This ): U[] @@ -145,7 +145,7 @@ interface Array { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|U[], + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, thisArg?: This ): U[] diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index e7fcfc6ff5d..5823233a25b 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -827,15 +827,17 @@ declare namespace ts.server.protocol { /** * Information about the item to be renamed. */ - interface RenameInfo { + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { /** * True if item can be renamed. */ - canRename: boolean; + canRename: true; /** - * Error message if item can not be renamed. + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ - localizedErrorMessage?: string; + fileToRename?: string; /** * Display name of the item to be renamed. */ @@ -852,6 +854,15 @@ declare namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; } /** * A group of text spans, all in 'file'. @@ -860,7 +871,11 @@ declare namespace ts.server.protocol { /** The file to which the spans apply */ file: string; /** The text spans in this group */ - locs: TextSpan[]; + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface RenameResponseBody { /** @@ -1373,7 +1388,7 @@ declare namespace ts.server.protocol { * begin with prefix. */ interface CompletionsRequest extends FileLocationRequest { - command: CommandTypes.Completions; + command: CommandTypes.Completions | CommandTypes.CompletionInfo; arguments: CompletionsRequestArgs; } /** @@ -1885,6 +1900,35 @@ declare namespace ts.server.protocol { */ openFiles: string[]; } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } type LargeFileReferencedEventName = "largeFileReferenced"; interface LargeFileReferencedEvent extends Event { event: LargeFileReferencedEventName; @@ -2220,6 +2264,7 @@ declare namespace ts.server.protocol { readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; } interface CompilerOptions { allowJs?: boolean; diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index 509172c0ead..de74fa7bdcd 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -61,7 +61,7 @@ "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Uma propriedade de uma interface ou tipo literal cujo tipo é um tipo de 'unique symbol' deve ser 'readonly'.", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Um parâmetro obrigatório não pode seguir um parâmetro opcional.", "A_rest_element_cannot_contain_a_binding_pattern_2501": "Um elemento rest não pode conter um padrão de associação.", - "A_rest_element_cannot_have_a_property_name_2566": "Um elemento restante não pode ter um nome de propriedade.", + "A_rest_element_cannot_have_a_property_name_2566": "Um elemento rest não pode ter um nome de propriedade.", "A_rest_element_cannot_have_an_initializer_1186": "Um elemento rest não pode ter um inicializador.", "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Um elemento rest deve ser o último em um padrão de desestruturação.", "A_rest_parameter_cannot_be_optional_1047": "Um parâmetro rest não pode ser opcional.", @@ -174,7 +174,7 @@ "An_object_member_cannot_be_declared_optional_1162": "Um membro de objeto não pode ser declarado como opcional.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "A assinatura de sobrecarga não pode ser declarada como geradora.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Uma expressão unária com o operador '{0}' não é permitida no lado esquerdo de uma expressão de exponenciação. Considere delimitar a expressão em parênteses.", - "Annotate_everything_with_types_from_JSDoc_95043": "Anotar tudo com tipos de JSDoc", + "Annotate_everything_with_types_from_JSDoc_95043": "Anotar tudo com tipos do JSDoc", "Annotate_with_type_from_JSDoc_95009": "Anotar com o tipo do JSDoc", "Annotate_with_types_from_JSDoc_95010": "Anotar com os tipos do JSDoc", "Argument_expression_expected_1135": "Expressão de argumento esperada.", @@ -368,7 +368,7 @@ "Enables_experimental_support_for_ES7_decorators_6065": "Habilita o suporte experimental para decoradores ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita o suporte experimental para a emissão de tipo de metadados para decoradores.", "Enum_0_used_before_its_declaration_2450": "A enumeração '{0}' usada antes de sua declaração.", - "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações de enum apenas podem se mescladas com namespaces ou com outras declarações de enum.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações enum só podem ser mescladas com namespaces ou com outras declarações enum.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Declarações de enumeração devem ser const ou não const.", "Enum_member_expected_1132": "Membro de enumeração esperado.", "Enum_member_must_have_initializer_1061": "O membro de enumeração deve ter um inicializador.", @@ -571,7 +571,7 @@ "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "O módulo {0} já exportou um membro denominado '{1}'. Considere reexportar explicitamente para resolver a ambiguidade.", "Module_0_has_no_default_export_1192": "O módulo '{0}' não tem padrão de exportação.", "Module_0_has_no_exported_member_1_2305": "O módulo '{0}' não tem nenhum membro exportado '{1}'.", - "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "O módulo '{0}' não tem nenhum membro exportado '{1}'. Você quis dizer '{2}'?", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "O módulo '{0}' não tem nenhum membro '{1}' exportado. Você quis dizer '{2}'?", "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "O módulo '{0}' está oculto por uma declaração de local com o mesmo nome.", "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "O módulo '{0}' resolve para uma entidade sem módulo e não pode ser importado usando este constructo.", "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "O módulo '{0}' usa 'export =' e não pode ser usado com 'export *'.", @@ -622,7 +622,7 @@ "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "A opção '{0} só pode ser usada quando qualquer uma das opções '--inlineSourceMap' ou '--sourceMap' é fornecida.", "Option_0_cannot_be_specified_with_option_1_5053": "A opção '{0}' não pode ser especificada com a opção '{1}'.", "Option_0_cannot_be_specified_without_specifying_option_1_5052": "A opção '{0}' não pode ser especificada sem especificar a opção '{1}'.", - "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "A opção '{0}' não pode ser especificada sem especificar a opção '{1}' ou a opção '{2}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "A opção '{0}' não pode ser especificada sem a especificação da opção '{1}' ou '{2}'.", "Option_0_should_have_array_of_strings_as_a_value_6103": "A opção '{0}' deve ter matriz de cadeias de um valor.", "Option_build_must_be_the_first_command_line_argument_6369": "A opção '--build' precisa ser o primeiro argumento da linha de comando.", "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.", @@ -686,7 +686,7 @@ "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "O projeto '{0}' está atualizado com os arquivos .d.ts de suas dependências", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Referências de projeto não podem formar um gráfico circular. Ciclo detectado: {0}", "Projects_in_this_build_Colon_0_6355": "Projetos neste build: {0}", - "Projects_to_reference_6300": "Projetos para referência", + "Projects_to_reference_6300": "Projetos a serem referenciados", "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'?", @@ -740,7 +740,7 @@ "Remove_braces_from_arrow_function_95060": "Remover chaves da função de seta", "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}'", + "Remove_import_from_0_90005": "Remover importação de '{0}'", "Remove_unreachable_code_95050": "Remover código inacessível", "Remove_unused_label_95053": "Remover rótulo não utilizado", "Remove_variable_statement_90010": "Remover instrução de variável", @@ -752,7 +752,7 @@ "Report_errors_on_unused_parameters_6135": "Relatar erros nos parâmetros não utilizados.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Os parâmetros de tipo necessários podem não seguir os parâmetros de tipo opcionais.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "A resolução para o módulo '{0}' foi encontrada no cache do local '{1}'.", - "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolva 'keyof' para nomes de propriedades com valores de cadeia de caracteres somente (sem números ou símbolos).", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolva 'keyof' somente para nomes de propriedades com valores de cadeia de caracteres (sem números nem símbolos).", "Resolving_from_node_modules_folder_6118": "Resolvendo na pasta node_modules...", "Resolving_module_0_from_1_6086": "======== Resolvendo módulo '{0}' de '{1}'. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolvendo nome de módulo '{0}' relativo à URL base '{1}' - '{2}'.", @@ -803,8 +803,8 @@ "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Mostrar o que seria compilado (ou excluído, se especificado com '--clean')", "Signature_0_must_be_a_type_predicate_1224": "A assinatura '{0}' deve ser um predicado de tipo.", "Skip_type_checking_of_declaration_files_6012": "Ignorar a verificação de tipo dos arquivos de declaração.", - "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Ignorando build do projeto '{0}' porque sua dependência '{1}' tem erros", - "Skipping_clean_because_not_all_projects_could_be_located_6371": "Ignorando a limpeza porque nem todos os projetos foram localizados", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Ignorando o build do projeto '{0}' porque a dependência '{1}' tem erros", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Ignorando a limpeza porque não foram localizados todos os projetos", "Source_Map_Options_6175": "Opções do Sourcemap", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "A assinatura de sobrecarga especializada não pode ser atribuída a qualquer assinatura não especializada.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "O especificador de importação dinâmica não pode ser o elemento de difusão.", @@ -966,7 +966,7 @@ "Unexpected_end_of_text_1126": "Fim inesperado do texto.", "Unexpected_token_1012": "Token inesperado.", "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token inesperado. Um construtor, método, acessador ou propriedade era esperado.", - "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Um nome de parâmetro de tipo era esperado sem chaves.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Era esperado um nome de parâmetro de tipo sem chaves.", "Unexpected_token_expected_1179": "Token inesperado. '{' esperado.", "Unknown_compiler_option_0_5023": "Opção do compilador '{0}' desconhecida.", "Unknown_option_excludes_Did_you_mean_exclude_6114": "Opção desconhecida 'excludes'. Você quis dizer 'exclude'?", @@ -993,7 +993,7 @@ "Variable_declaration_list_cannot_be_empty_1123": "A lista de declaração de variável não pode estar vazia.", "Version_0_6029": "Versão {0}", "Watch_input_files_6005": "Observe os arquivos de entrada.", - "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se se deve manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se é necessário manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Não é possível renomear elementos que são definidos na biblioteca TypeScript padrão.", "You_cannot_rename_this_element_8000": "Você não pode renomear este elemento.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' aceita muito poucos argumentos para serem usados como um decorador aqui. Você quis dizer para chamá-lo primeiro e gravar '@{0}()'?", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 611ccb3a4ad..284c223d0cd 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -49,8 +49,8 @@ "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden önce gelemez.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Ad alanı bildirimine yalnızca bir ad alanında veya modülde izin verilir.", "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Bir ad alanı stili içeri aktarma işlemi çağrılamadığından veya oluşturulamadığından çalışma zamanında hataya yol açacak.", - "A_non_dry_build_would_build_project_0_6357": "non-dry bir derleme '{0}' projesini derler", - "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "non-dry bir derleme şu dosyaları siler: {0}", + "A_non_dry_build_would_build_project_0_6357": "-dry bayrağı kullanılmayan bir derleme '{0}' projesini derler", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "-dry bayrağı kullanılmayan bir derleme şu dosyaları siler: {0}", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Parametre başlatıcısına yalnızca bir işlevde veya oluşturucu uygulamasında izin verilir.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Parametre özelliği, rest parametresi kullanılarak bildirilemez.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Parametre özelliğine yalnızca bir oluşturucu uygulamasında izin verilir.", @@ -110,7 +110,7 @@ "Add_initializers_to_all_uninitialized_properties_95027": "Tüm başlatılmamış özelliklere başlatıcılar ekle", "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekle", "Add_missing_typeof_95052": "Eksik 'typeof' öğesini ekle", - "Add_or_remove_braces_in_an_arrow_function_95058": "Ok işlevine küme ayracı ekleyin veya kaldırın", + "Add_or_remove_braces_in_an_arrow_function_95058": "Ok işlevine küme ayracı ekle veya kaldır", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Bir üye adıyla eşleşen tüm çözülmemiş değişkenlere niteleyici ekle", "Add_to_all_uncalled_decorators_95044": "Çağrılmayan tüm dekoratörlere '()' ekle", "Add_ts_ignore_to_all_error_messages_95042": "Tüm hata iletilerine '@ts-ignore' ekle", @@ -122,7 +122,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Tüm '{0}' bildirimleri aynı değiştiricilere sahip olmalıdır.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tüm '{0}' bildirimleri özdeş tür parametrelerine sahip olmalıdır.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Soyut metoda ait tüm bildirimler ardışık olmalıdır.", - "All_destructured_elements_are_unused_6198": "Yok edilen öğelerin hiçbiri kullanılmamış.", + "All_destructured_elements_are_unused_6198": "Yapısı bozulan öğelerin hiçbiri kullanılmıyor.", "All_imports_in_import_declaration_are_unused_6192": "İçeri aktarma bildirimindeki hiçbir içeri aktarma kullanılmadı.", "All_variables_are_unused_6199": "Hiçbir değişken kullanılmıyor.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.", @@ -232,7 +232,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Muhtemelen 'null' olan bir nesne çağrılamıyor.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Muhtemelen 'null' veya 'undefined' olan bir nesne çağrılamıyor.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Muhtemelen 'undefined' olan bir nesne çağrılamıyor.", - "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' projesi, 'outFile' kümesi içermediğinden başa eklenemiyor", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "{0}' projesi için 'outFile' ayarlanmadığından başa eklenemiyor", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' bayrağı sağlandığında bir tür yeniden dışarı aktarılamaz.", "Cannot_read_file_0_Colon_1_5012": "'{0}' dosyası okunamıyor: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Blok kapsamlı değişken '{0}', yeniden bildirilemiyor.", @@ -311,7 +311,7 @@ "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekoratörler aynı ada sahip birden fazla get/set erişimcisine uygulanamaz.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Modülün varsayılan dışarı aktarımı '{0}' özel adına sahip veya bu adı kullanıyor.", "Delete_all_unused_declarations_95024": "Kullanılmayan tüm bildirimleri sil", - "Delete_the_outputs_of_all_projects_6365": "Tüm projelerin çıkışlarını silin", + "Delete_the_outputs_of_all_projects_6365": "Tüm projelerin çıkışlarını sil", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Kullanım Dışı] Bunun yerine '--jsxFactory' kullanın. 'react' JSX gösterimi hedefleniyorsa, createElement için çağrılan nesneyi belirtin", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Kullanım Dışı] Bunun yerine '--outFile' kullanın. Çıkışı tek bir dosya olarak birleştirin ve gösterin", "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Kullanım Dışı] Bunun yerine '--skipLibCheck' kullanın. Varsayılan kitaplık bildirim dosyalarının tür denetimini atlayın.", @@ -362,13 +362,13 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Sınıflarda sıkı özellik başlatma denetimini etkinleştirin.", "Enable_strict_null_checks_6113": "Katı null denetimlerini etkinleştir.", "Enable_tracing_of_the_name_resolution_process_6085": "Ad çözümleme işlemini izlemeyi etkinleştir.", - "Enable_verbose_logging_6366": "Ayrıntılı günlüğe yazmayı etkinleştirin", + "Enable_verbose_logging_6366": "Ayrıntılı günlüğe yazmayı etkinleştir", "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Tüm içeri aktarma işlemleri için ad alanı nesnelerinin oluşturulması aracılığıyla CommonJS ile ES Modülleri arasında yayımlama birlikte çalışabilirliğine imkan tanır. Şu anlama gelir: 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Zaman uyumsuz ES7 işlevleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_ES7_decorators_6065": "ES7 dekoratörleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Dekoratörlere tür meta verisi gönderme için deneysel desteği etkinleştirir.", "Enum_0_used_before_its_declaration_2450": "'{0}' sabit listesi, bildiriminden önce kullanıldı.", - "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Enum bildirimleri yalnızca ad alanı veya diğer enum bildirimleri ile birleştirilebilir.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Sabit listesi bildirimleri yalnızca ad alanı veya diğer sabit listesi bildirimleri ile birleştirilebilir.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Sabit listesi bildirimlerinin tümü const veya const olmayan değerler olmalıdır.", "Enum_member_expected_1132": "Sabit listesi üyesi bekleniyor.", "Enum_member_must_have_initializer_1061": "Sabit listesi üyesi bir başlatıcıya sahip olmalıdır.", @@ -571,7 +571,7 @@ "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "{0} modülü, '{1}' adlı bir üyeyi zaten dışarı aktardı. Belirsizliği çözmek için açık olarak yeniden dışarı aktarmayı göz önünde bulundurun.", "Module_0_has_no_default_export_1192": "'{0}' modülü için varsayılan dışarı aktarma yok.", "Module_0_has_no_exported_member_1_2305": "'{0}' modülü, dışarı aktarılan '{1}' üyesine sahip değil.", - "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "'{0}' modülünün dışa aktarılan '{1}' adlı bir üyesi yok. Şunu mu demek istediniz: '{2}'?", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "{0}' modülünün dışarı aktarılan '{1}' adlı bir üyesi yok. Şunu mu demek istediniz: '{2}'?", "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "'{0}' modülü, aynı ada sahip bir yerel bildirim tarafından gizleniyor.", "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "'{0}' modülü, modül olmayan bir varlığa çözümleniyor ve bu oluşturma ile içeri aktarılamaz.", "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "'{0}' modülü 'export =' kullanıyor ve 'export *' ile birlikte kullanılamaz.", @@ -737,7 +737,7 @@ "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Başvurulan proje '{0}' \"composite\": true ayarına sahip olmalıdır.", "Remove_all_unreachable_code_95051": "Tüm erişilemeyen kodları kaldır", "Remove_all_unused_labels_95054": "Kullanılmayan tüm etiketleri kaldır", - "Remove_braces_from_arrow_function_95060": "Ok işlevinden köşeli ayraçları kaldırın", + "Remove_braces_from_arrow_function_95060": "Ok işlevinden küme ayraçlarını kaldır", "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldır", "Remove_destructuring_90009": "Yıkmayı kaldır", "Remove_import_from_0_90005": "'{0}' öğesinden içeri aktarmayı kaldır", diff --git a/lib/tsc.js b/lib/tsc.js index 7a7216cf020..6309a02f3fe 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -59,10 +59,11 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook }; var ts; (function (ts) { - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -661,16 +662,13 @@ var ts; return result; } function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -712,7 +710,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1011,7 +1009,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1125,6 +1123,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1276,7 +1278,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1673,6 +1677,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); var ts; (function (ts) { @@ -1732,6 +1740,287 @@ var ts; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + var Version = (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + if (this === other) + return 0; + if (other === undefined) + return 1; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + if (left === right) + return 0; + if (left.length === 0) + return right.length === 0 ? 0 : 1; + if (right.length === 0) + return -1; + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 : 1; + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + return ts.compareValues(left.length, right.length); + } + var VersionRange = (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); +var ts; (function (ts) { var OperationCanceledException = (function () { function OperationCanceledException() { @@ -1840,19 +2129,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; ts.missingFileModifiedTime = new Date(0); function createPollingIntervalBasedLevels(levels) { var _a; @@ -2048,17 +2324,20 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; function createRecursiveDirectoryWatcher(host) { var cache = ts.createMap(); var callbackCache = ts.createMultiMap(); @@ -2331,10 +2610,11 @@ var ts; } function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { - var fileName = !ts.isString(relativeFileName) - ? undefined - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -2885,7 +3165,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -2924,6 +3204,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -3167,7 +3451,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -3195,6 +3478,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -3286,6 +3577,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -3399,7 +3691,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -3493,7 +3787,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -3591,6 +3885,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -3621,9 +3924,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -3688,6 +3991,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -3816,10 +4120,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; function tokenIsIdentifierOrKeyword(token) { return token >= 71; } @@ -3828,136 +4135,85 @@ var ts; return token === 29 || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117, - "any": 119, - "as": 118, - "boolean": 122, - "break": 72, - "case": 73, - "catch": 74, - "class": 75, - "continue": 77, - "const": 76, - "constructor": 123, - "debugger": 78, - "declare": 124, - "default": 79, - "delete": 80, - "do": 81, - "else": 82, - "enum": 83, - "export": 84, - "extends": 85, - "false": 86, - "finally": 87, - "for": 88, - "from": 143, - "function": 89, - "get": 125, - "if": 90, - "implements": 108, - "import": 91, - "in": 92, - "infer": 126, - "instanceof": 93, - "interface": 109, - "is": 127, - "keyof": 128, - "let": 110, - "module": 129, - "namespace": 130, - "never": 131, - "new": 94, - "null": 95, - "number": 134, - "object": 135, - "package": 111, - "private": 112, - "protected": 113, - "public": 114, - "readonly": 132, - "require": 133, - "global": 144, - "return": 96, - "set": 136, - "static": 115, - "string": 137, - "super": 97, - "switch": 98, - "symbol": 138, - "this": 99, - "throw": 100, - "true": 101, - "try": 102, - "type": 139, - "typeof": 103, - "undefined": 140, - "unique": 141, - "unknown": 142, - "var": 104, - "void": 105, - "while": 106, - "with": 107, - "yield": 116, - "async": 120, - "await": 121, - "of": 145, - "{": 17, - "}": 18, - "(": 19, - ")": 20, - "[": 21, - "]": 22, - ".": 23, - "...": 24, - ";": 25, - ",": 26, - "<": 27, - ">": 29, - "<=": 30, - ">=": 31, - "==": 32, - "!=": 33, - "===": 34, - "!==": 35, - "=>": 36, - "+": 37, - "-": 38, - "**": 40, - "*": 39, - "/": 41, - "%": 42, - "++": 43, - "--": 44, - "<<": 45, - ">": 46, - ">>>": 47, - "&": 48, - "|": 49, - "^": 50, - "!": 51, - "~": 52, - "&&": 53, - "||": 54, - "?": 55, - ":": 56, - "=": 58, - "+=": 59, - "-=": 60, - "*=": 61, - "**=": 62, - "/=": 63, - "%=": 64, - "<<=": 65, - ">>=": 66, - ">>>=": 67, - "&=": 68, - "|=": 69, - "^=": 70, - "@": 57, - }); + var textToKeywordObj = (_a = { + abstract: 117, + any: 119, + as: 118, + boolean: 122, + break: 72, + case: 73, + catch: 74, + class: 75, + continue: 77, + const: 76 + }, + _a["" + "constructor"] = 123, + _a.debugger = 78, + _a.declare = 124, + _a.default = 79, + _a.delete = 80, + _a.do = 81, + _a.else = 82, + _a.enum = 83, + _a.export = 84, + _a.extends = 85, + _a.false = 86, + _a.finally = 87, + _a.for = 88, + _a.from = 143, + _a.function = 89, + _a.get = 125, + _a.if = 90, + _a.implements = 108, + _a.import = 91, + _a.in = 92, + _a.infer = 126, + _a.instanceof = 93, + _a.interface = 109, + _a.is = 127, + _a.keyof = 128, + _a.let = 110, + _a.module = 129, + _a.namespace = 130, + _a.never = 131, + _a.new = 94, + _a.null = 95, + _a.number = 134, + _a.object = 135, + _a.package = 111, + _a.private = 112, + _a.protected = 113, + _a.public = 114, + _a.readonly = 132, + _a.require = 133, + _a.global = 144, + _a.return = 96, + _a.set = 136, + _a.static = 115, + _a.string = 137, + _a.super = 97, + _a.switch = 98, + _a.symbol = 138, + _a.this = 99, + _a.throw = 100, + _a.true = 101, + _a.try = 102, + _a.type = 139, + _a.typeof = 103, + _a.undefined = 140, + _a.unique = 141, + _a.unknown = 142, + _a.var = 104, + _a.void = 105, + _a.while = 106, + _a.with = 107, + _a.yield = 116, + _a.async = 120, + _a.await = 121, + _a.of = 145, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17, "}": 18, "(": 19, ")": 20, "[": 21, "]": 22, ".": 23, "...": 24, ";": 25, ",": 26, "<": 27, ">": 29, "<=": 30, ">=": 31, "==": 32, "!=": 33, "===": 34, "!==": 35, "=>": 36, "+": 37, "-": 38, "**": 40, "*": 39, "/": 41, "%": 42, "++": 43, "--": 44, "<<": 45, ">": 46, ">>>": 47, "&": 48, "|": 49, "^": 50, "!": 51, "~": 52, "&&": 53, "||": 54, "?": 55, ":": 56, "=": 58, "+=": 59, "-=": 60, "*=": 61, "**=": 62, "/=": 63, "%=": 64, "<<=": 65, ">>=": 66, ">>>=": 67, "&=": 68, "|=": 69, "^=": 70, "@": 57 })); var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -4418,6 +4674,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -4447,6 +4704,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -4814,9 +5072,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 && ch <= 122) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -4867,6 +5125,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -4903,6 +5162,24 @@ var ts; case 11: case 12: case 32: + case 160: + case 5760: + case 8192: + case 8193: + case 8194: + case 8195: + case 8196: + case 8197: + case 8198: + case 8199: + case 8200: + case 8201: + case 8202: + case 8203: + case 8239: + case 8287: + case 12288: + case 65279: if (skipTrivia) { pos++; continue; @@ -4960,6 +5237,10 @@ var ts; return pos += 2, token = 40; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1)) { + asteriskSeen = true; + continue; + } return token = 39; case 43: if (text.charCodeAt(pos + 1) === 43) { @@ -5437,7 +5718,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71; + return token = getIdentifierToken(); } else { return token = 0; @@ -5512,6 +5793,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -5527,7 +5811,6 @@ var ts; ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; })(ts || (ts = {})); (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -5606,22 +5889,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -5726,6 +5996,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -5901,12 +6177,19 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -5926,11 +6209,11 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216) ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: if (node.singleQuote) { @@ -6267,6 +6550,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2); } @@ -6326,6 +6613,7 @@ var ts; case 137: case 122: case 138: + case 135: case 140: case 131: return true; @@ -6926,18 +7214,18 @@ var ts; return node.kind === 246 && node.moduleReference.kind !== 257; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216); } @@ -6977,14 +7265,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -7007,14 +7295,18 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -7022,20 +7314,20 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - function getDeclaredJavascriptInitializer(node) { + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; - function getAssignedJavascriptInitializer(node) { + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 || e.kind === 195 ? initializer : undefined; @@ -7049,21 +7341,21 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + ts.getExpandoInitializer = getExpandoInitializer; + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 && ts.isIdentifier(parent.left)) { @@ -7074,7 +7366,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; function isSameEntityName(name, initializer) { if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { return name.escapedText === initializer.escapedText; @@ -7107,12 +7399,12 @@ var ts; return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 || isInJavaScriptFile(expr) ? special : 0; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 || isInJSFile(expr) ? special : 0; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 || !ts.isPropertyAccessExpression(expr.left)) { return 0; @@ -7121,9 +7413,9 @@ var ts; if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { return 6; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99) { return 4; } @@ -7148,7 +7440,7 @@ var ts; } return 0; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -7157,11 +7449,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 && !!ts.getJSDocTypeTag(expr.parent); } @@ -7267,7 +7559,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 && + getAssignmentDeclarationKind(node.expression) !== 0 && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 ? node.expression.right.right @@ -7308,6 +7600,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -7477,6 +7773,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193) { + node = node.parent; + } + return node; + } function isDeleteTarget(node) { if (node.kind !== 187 && node.kind !== 188) { return false; @@ -7498,32 +7800,35 @@ var ts; return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } ts.isDeclarationName = isDeclarationName; - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71: case 9: - case 8: { - var parent = name.parent; + case 8: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + case 71: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 && + getAssignmentDeclarationKind(binExp) !== 0 && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 147 && @@ -7569,7 +7874,7 @@ var ts; node.kind === 251 || node.kind === 255 || node.kind === 252 && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -7578,7 +7883,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { var tag = ts.getJSDocAugmentsTag(node); if (tag) { return tag.class; @@ -8251,7 +8556,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); @@ -8263,7 +8568,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -8377,7 +8682,7 @@ var ts; ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -8389,7 +8694,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -8623,13 +8928,18 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -8651,15 +8961,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 || isPropertyAccessEntityNameExpression(node); } @@ -8694,10 +8995,10 @@ var ts; function isExportDefaultSymbol(symbol) { return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512); } - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -8818,6 +9119,26 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -8899,6 +9220,8 @@ var ts; } ts.formatObjectFlags = formatObjectFlags; function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -9030,6 +9353,8 @@ var ts; if (!parent) return 0; switch (parent.kind) { + case 193: + return accessKind(parent); case 201: case 200: var operator = parent.operator; @@ -9041,11 +9366,31 @@ var ts; : 0; case 187: return parent.name !== node ? 0 : accessKind(parent); + case 273: { + var parentAccess = accessKind(parent.parent); + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274: + return node === parent.objectAssignmentInitializer ? 0 : accessKind(parent.parent); + case 185: + return accessKind(parent); default: return 0; } function writeOrReadWrite() { - return parent.parent && parent.parent.kind === 219 ? 1 : 2; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 ? 1 : 2; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0: + return 1; + case 1: + return 0; + case 2: + return 2; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -9254,12 +9599,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -9469,7 +9808,7 @@ var ts; if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219: var expr = hostNode.expression; switch (expr.kind) { @@ -9481,9 +9820,7 @@ var ts; return arg; } } - return undefined; - case 1: - return undefined; + break; case 193: { return getDeclarationIdentifier(hostNode.expression); } @@ -9491,10 +9828,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -9523,7 +9858,7 @@ var ts; } case 202: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1: case 4: case 5: @@ -9584,6 +9919,13 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; function hasJSDocParameterTags(node) { return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } @@ -9671,7 +10013,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -10917,7 +11272,7 @@ var ts; } function isDeclaration(node) { if (node.kind === 148) { - return node.parent.kind !== 301 || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -11269,6 +11624,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -11285,9 +11652,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -11299,13 +11665,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -11498,8 +11865,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -11694,6 +12059,13 @@ var ts; } ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42, 63]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -11739,6 +12111,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; function isImplicitGlob(lastPathComponent) { return !/[.*?]/.test(lastPathComponent); } @@ -11925,35 +12298,56 @@ var ts; } } ts.getScriptKindFromFileName = getScriptKindFromFileName; - ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; - ts.supportedJavascriptExtensions = [".js", ".jsx"]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedTSExtensionsWithJson = [".ts", ".tsx", ".d.ts", ".json"]; + ts.supportedTSExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; + ts.supportedJSExtensions = [".js", ".jsx"]; + ts.supportedJSAndJsonExtensions = [".js", ".jsx", ".json"]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json"]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json"]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 || scriptKind === 2; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -12057,14 +12451,14 @@ var ts; return !(pos >= 0); } ts.positionIsSynthesized = positionIsSynthesized; - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json"; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json"; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); @@ -12219,6 +12613,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -12282,6 +12692,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275: @@ -12352,6 +12763,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -12710,7 +13122,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, 6); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); @@ -12776,8 +13188,12 @@ var ts; if (scriptKind === 6) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -13338,7 +13754,15 @@ var ts; case 6: return token() === 21 || isLiteralPropertyName(); case 12: - return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); + switch (token()) { + case 21: + case 39: + case 24: + case 23: + return true; + default: + return isLiteralPropertyName(); + } case 18: return isLiteralPropertyName(); case 9: @@ -13940,8 +14364,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288, dotdotdot.pos); variadic.type = type; @@ -15554,6 +15980,7 @@ var ts; var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); node.questionToken = parseOptionalToken(55); + node.exclamationToken = parseOptionalToken(51); if (asteriskToken || token() === 19 || token() === 27) { return parseMethodDeclaration(node, asteriskToken); } @@ -16749,7 +17176,7 @@ var ts; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281, scanner.getTokenPos()); + var result = createNode(281); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17); result.type = doInsideOfContext(2097152, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -16852,10 +17279,6 @@ var ts; indent += asterisk.length; } break; - case 71: - pushComment(scanner.getTokenText()); - state = 2; - break; case 5: var whitespace = scanner.getTokenText(); if (state === 2) { @@ -16938,7 +17361,7 @@ var ts; var atToken = createNode(57, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -17109,10 +17532,8 @@ var ts; var result = target === 1 ? createNode(303, atToken.pos) : createNode(297, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -17126,14 +17547,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 || child.kind === 303) { children = ts.append(children, child); } @@ -17221,7 +17642,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -17236,7 +17657,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290, start_3); } @@ -17296,7 +17717,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -17336,17 +17757,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 || child.kind === 303) && target !== 4 && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -17374,7 +17795,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57); var atToken = createNode(57); atToken.end = scanner.getTextPos(); @@ -17400,9 +17821,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { var constraint; @@ -18014,7 +18433,7 @@ var ts; ]; ts.libs = libEntries.map(function (entry) { return entry[0]; }); ts.libMap = ts.createMapFromEntries(libEntries); - ts.optionDeclarations = [ + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -18028,6 +18447,41 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -18075,21 +18529,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, { name: "target", shortName: "t", @@ -18103,6 +18542,8 @@ var ts; es2018: 5, esnext: 6, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18121,6 +18562,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18133,6 +18575,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -18140,6 +18583,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -18157,6 +18601,7 @@ var ts; "react-native": 3, "react": 2 }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18265,6 +18710,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18273,6 +18719,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18281,14 +18728,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18297,6 +18754,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18305,6 +18763,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18337,6 +18796,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -18348,6 +18808,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -18355,6 +18816,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -18362,6 +18824,7 @@ var ts; { name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -18375,6 +18838,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -18386,6 +18850,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -18396,6 +18861,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -18477,30 +18943,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -18558,12 +19006,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -18576,6 +19026,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -18621,6 +19072,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -18628,6 +19080,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -18681,7 +19134,41 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); ts.typeAcquisitionDeclarations = [ { name: "enableAutoDiscovery", @@ -18727,20 +19214,20 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } @@ -18773,16 +19260,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -18794,14 +19280,14 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); } else { if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -18834,7 +19320,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -18877,8 +19363,18 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -18890,7 +19386,32 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + projects.push("."); + } + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -19162,7 +19683,10 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -19414,7 +19938,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -19431,8 +19956,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -19468,19 +20007,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -19488,7 +20026,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -19505,12 +20042,28 @@ var ts; function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -19588,11 +20141,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -19638,7 +20186,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -19646,7 +20194,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -19792,7 +20340,7 @@ var ts; validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { @@ -19801,8 +20349,10 @@ var ts; var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); if (filesSpecs) { for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { var fileName = filesSpecs_1[_i]; @@ -19810,27 +20360,42 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json")) { + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json"); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -19981,6 +20546,12 @@ var ts; function noPackageId(r) { return withPackageId(undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } var Extensions; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; @@ -19992,7 +20563,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -20001,45 +20572,92 @@ var ts; failedLookupLocations: failedLookupLocations }; } - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return path; } } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; - } - return result.config; - } - catch (e) { - return {}; - } - } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -20073,7 +20691,8 @@ var ts; var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -20093,7 +20712,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -20119,11 +20737,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -20138,7 +20756,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, false, moduleResolutionState, true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -20167,10 +20792,13 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + if (baseFileName.charCodeAt(0) !== 46) { + result.push(baseFileName); + } } } } @@ -20312,15 +20940,15 @@ var ts; return result; } ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -20354,7 +20982,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -20371,7 +20999,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -20382,66 +21010,53 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -20453,8 +21068,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -20462,7 +21077,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -20475,7 +21090,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, false, state, true); return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } @@ -20491,29 +21106,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -20521,7 +21137,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } ts.nodeModulesPathPart = "/node_modules/"; function parseNodeModuleFromPath(resolved) { @@ -20550,41 +21166,37 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); - } - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json"); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -20598,11 +21210,11 @@ var ts; return tryExtension(".json"); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -20616,40 +21228,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { - var path = tryReadPackageJsonFields(true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts"; } @@ -20661,6 +21266,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts")) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -20672,46 +21278,51 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { - file = tryReadPackageJsonFields(false, jsonContent, candidate, state); - if (!file) { - return undefined; + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); - if (result) { - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } function resolvedIfExtensionMatches(extensions, path) { var ext = ts.tryGetExtensionFromPath(path); @@ -20729,90 +21340,132 @@ var ts; return extension === ".d.ts"; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, true, undefined); + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, true, undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } return mangled; } function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -20821,63 +21474,64 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; - function getPackageNameFromAtTypesDirectory(mangledName) { + ts.mangleScopedPackageName = mangleScopedPackageName; + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; - function getUnmangledNameForScopedPackage(typesPackageName) { + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } if (!ts.isExternalModuleNameRelative(moduleName)) { var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, false, state)); } } } @@ -20887,9 +21541,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, false); return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -21046,12 +21700,16 @@ var ts; if (symbolFlags & (32 | 64 | 2048 | 4096) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + symbol.valueDeclaration = node; } } function getDeclarationName(node) { @@ -21091,7 +21749,7 @@ var ts; case 277: return "export="; case 202: - if (ts.getSpecialPropertyAssignmentKind(node) === 2) { + if (ts.getAssignmentDeclarationKind(node) === 2) { return "export="; } ts.Debug.fail("Unknown binary declaration kind"); @@ -21133,7 +21791,7 @@ var ts; if (symbol.isReplaceableByMethod) { symbolTable.set(name, symbol = createSymbol(0, name)); } - else { + else if (!(includes & 3 && symbol.flags & 67108864)) { if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -21188,12 +21846,12 @@ var ts; } else { if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } - var exportKind = symbolFlags & 67216319 ? 1048576 : 0; + var exportKind = symbolFlags & 67220415 ? 1048576 : 0; var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -21328,6 +21986,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -21425,6 +22084,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200: return expr.operator === 51 && isNarrowingExpression(expr.operand); + case 197: + return isNarrowingExpression(expr.expression); } return false; } @@ -21789,7 +22450,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -22147,7 +22807,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512, 67215503); + var symbol = declareSymbolAndAddToSymbolTable(node, 512, 110735); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -22164,7 +22824,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 67215503 : 0); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 110735 : 0); return state; } function bindFunctionOrConstructorType(node) { @@ -22232,9 +22892,6 @@ var ts; declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 67216319); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -22254,7 +22911,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288, 67901928); + bindBlockScopedDeclaration(typeAlias, 524288, 67897832); } else { bind(typeAlias.fullName); @@ -22426,7 +23083,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -22466,7 +23123,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288, 67901928); + bindBlockScopedDeclaration(parentNode, 524288, 67897832); break; } case 99: @@ -22482,15 +23139,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, undefined, node.expression, 1 | 134217728, 67216318); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, undefined, node.expression, 1 | 134217728, 67220414); } break; case 202: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1: bindExportsPropertyAssignment(node); @@ -22558,15 +23215,15 @@ var ts; return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 154: case 153: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67208127); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67212223); case 237: return bindFunctionDeclaration(node); case 155: return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 156: - return bindPropertyOrMethodOrAccessor(node, 32768, 67150783); + return bindPropertyOrMethodOrAccessor(node, 32768, 67154879); case 157: - return bindPropertyOrMethodOrAccessor(node, 65536, 67183551); + return bindPropertyOrMethodOrAccessor(node, 65536, 67187647); case 163: case 287: case 291: @@ -22582,7 +23239,7 @@ var ts; case 195: return bindFunctionExpression(node); case 189: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -22591,9 +23248,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239: - return bindBlockScopedDeclaration(node, 64, 67901832); + return bindBlockScopedDeclaration(node, 64, 67897736); case 240: - return bindBlockScopedDeclaration(node, 524288, 67901928); + return bindBlockScopedDeclaration(node, 524288, 67897832); case 241: return bindEnumDeclaration(node); case 242: @@ -22668,33 +23325,30 @@ var ts; bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); } else { - var flags = node.kind === 252 && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) ? 2097152 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); + if (node.isExportEquals) { + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -22751,7 +23405,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, false); switch (thisContainer.kind) { case 237: @@ -22800,7 +23454,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, false); + bindPropertyAssignment(lhs.expression, lhs, false); } function bindPrototypePropertyAssignment(lhs, parent) { var classPrototype = lhs.expression; @@ -22813,7 +23467,7 @@ var ts; function bindSpecialPropertyAssignment(node) { var lhs = node.left; var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } node.left.parent = node; @@ -22831,36 +23485,36 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 : propertyAccess.parent.parent.kind === 277; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920))) { var flags_1 = 1536 | 67108864; - var excludeFlags_1 = 67215503 & ~67108864; + var excludeFlags_1 = 110735 & ~67108864; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 : 4) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 : 0) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 : 4; + var excludes = isMethod ? 67212223 : 0; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864, excludes & ~67108864); } - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 | 32 | 1024)) { return true; } @@ -22873,7 +23527,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 ? init.right : init, isPrototypeAssignment); } return false; } @@ -22945,14 +23599,17 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 : 0); + var enumExcludes = (isEnum ? 68008191 : 0); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 | enumFlags, 67220415 | enumExcludes); } else if (ts.isParameterDeclaration(node)) { - declareSymbolAndAddToSymbolTable(node, 1, 67216319); + declareSymbolAndAddToSymbolTable(node, 1, 67220415); } else { - declareSymbolAndAddToSymbolTable(node, 1, 67216318); + declareSymbolAndAddToSymbolTable(node, 1 | enumFlags, 67220414 | enumExcludes); } } } @@ -22967,7 +23624,7 @@ var ts; bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1, 67216319); + declareSymbolAndAddToSymbolTable(node, 1, 67220415); } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; @@ -22983,10 +23640,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16, 67215791); + bindBlockScopedDeclaration(node, 16, 67219887); } else { - declareSymbolAndAddToSymbolTable(node, 16, 67215791); + declareSymbolAndAddToSymbolTable(node, 16, 67219887); } } function bindFunctionExpression(node) { @@ -23024,10 +23681,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, undefined, node, 262144, 67639784); + declareSymbol(container_1.locals, undefined, node, 262144, 67635688); } else { - declareSymbolAndAddToSymbolTable(node, 262144, 67639784); + declareSymbolAndAddToSymbolTable(node, 262144, 67635688); } } else if (node.parent.kind === 174) { @@ -23036,14 +23693,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, undefined, node, 262144, 67639784); + declareSymbol(container_2.locals, undefined, node, 262144, 67635688); } else { bindAnonymousDeclaration(node, 262144, getDeclarationName(node)); } } else { - declareSymbolAndAddToSymbolTable(node, 262144, 67639784); + declareSymbolAndAddToSymbolTable(node, 262144, 67635688); } } function shouldReportErrorOnModuleDeclaration(node) { @@ -23057,8 +23714,7 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 218) || node.kind === 238 || - (node.kind === 242 && shouldReportErrorOnModuleDeclaration(node)) || - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -23085,7 +23741,7 @@ var ts; } } function isExecutableStatement(s) { - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 | 2)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } function isPurelyTypeDeclaration(s) { @@ -23121,6 +23777,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } function computeTransformFlagsForNode(node, subtreeFlags) { @@ -23190,32 +23849,32 @@ var ts; if (node.typeArguments) { transformFlags |= 3; } - if (subtreeFlags & 524288 - || (expression.transformFlags & (134217728 | 268435456))) { + if (subtreeFlags & 131072 + || (expression.transformFlags & (33554432 | 67108864))) { transformFlags |= 192; - if (expression.transformFlags & 268435456) { - transformFlags |= 16384; + if (expression.transformFlags & 67108864) { + transformFlags |= 8192; } } if (expression.kind === 91) { - transformFlags |= 67108864; - if (subtreeFlags & 16384) { - transformFlags |= 32768; + transformFlags |= 16777216; + if (subtreeFlags & 8192) { + transformFlags |= 16384; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~940049729; + return transformFlags & ~637666625; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3; } - if (subtreeFlags & 524288) { + if (subtreeFlags & 131072) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~940049729; + return transformFlags & ~637666625; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23232,7 +23891,7 @@ var ts; transformFlags |= 32; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23241,21 +23900,21 @@ var ts; var dotDotDotToken = node.dotDotDotToken; if (node.questionToken || node.type - || subtreeFlags & 4096 + || (subtreeFlags & 4096 && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (ts.hasModifier(node, 92)) { - transformFlags |= 3 | 262144; + transformFlags |= 3 | 4096; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { - transformFlags |= 192 | 131072; + if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { + transformFlags |= 192 | 65536; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23279,28 +23938,28 @@ var ts; } else { transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 274432) + if ((subtreeFlags & 4096) || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 32768) { + transformFlags |= 8192; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~942011713; + return transformFlags & ~638121281; } function computeClassExpression(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 274432 + if (subtreeFlags & 4096 || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 32768) { + transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~942011713; + return transformFlags & ~638121281; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23316,7 +23975,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23327,7 +23986,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~940574017; + return transformFlags & ~637797697; } function computeExpressionWithTypeArguments(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -23335,7 +23994,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23343,11 +24002,11 @@ var ts; || !node.body) { transformFlags |= 3; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003668801; + return transformFlags & ~653616449; } function computeMethod(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -23359,7 +24018,7 @@ var ts; || !node.body) { transformFlags |= 3; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } if (ts.hasModifier(node, 256)) { @@ -23369,7 +24028,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003668801; + return transformFlags & ~653616449; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23380,19 +24039,19 @@ var ts; || !node.body) { transformFlags |= 3; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003668801; + return transformFlags & ~653616449; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192; + transformFlags |= 4096; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -23402,7 +24061,7 @@ var ts; transformFlags = 3; } else { - transformFlags = subtreeFlags | 33554432; + transformFlags = subtreeFlags | 8388608; if (modifierFlags & 2270 || node.typeParameters || node.type) { @@ -23411,10 +24070,10 @@ var ts; if (modifierFlags & 256) { transformFlags |= node.asteriskToken ? 8 : 16; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 163840) { + if (subtreeFlags & 81920) { transformFlags |= 192; } if (node.asteriskToken) { @@ -23422,7 +24081,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003935041; + return transformFlags & ~653620545; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23434,17 +24093,17 @@ var ts; if (ts.hasModifier(node, 256)) { transformFlags |= node.asteriskToken ? 8 : 16; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 163840) { + if (subtreeFlags & 81920) { transformFlags |= 192; } if (node.asteriskToken) { transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003935041; + return transformFlags & ~653620545; } function computeArrowFunction(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -23456,46 +24115,46 @@ var ts; if (ts.hasModifier(node, 256)) { transformFlags |= 16; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 16384) { - transformFlags |= 32768; + if (subtreeFlags & 8192) { + transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003902273; + return transformFlags & ~653604161; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (transformFlags & 134217728) { - transformFlags ^= 134217728; - transformFlags |= 268435456; + if (transformFlags & 33554432) { + transformFlags ^= 33554432; + transformFlags |= 67108864 | 16 | 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~671089985; + return transformFlags & ~570426689; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionFlags = expression.transformFlags; - if (expressionFlags & 134217728) { - transformFlags &= ~134217728; - transformFlags |= 268435456; + if (expressionFlags & 33554432) { + transformFlags &= ~33554432; + transformFlags |= 67108864 | 16 | 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~671089985; + return transformFlags & ~570426689; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 | 8388608; - if (subtreeFlags & 1048576) { + transformFlags |= 192 | 2097152; + if (subtreeFlags & 262144) { transformFlags |= 8; } if (node.type) { transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -23505,21 +24164,21 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608) { + if (declarationListTransformFlags & 2097152) { transformFlags |= 192; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (subtreeFlags & 4194304 + if (subtreeFlags & 1048576 && ts.isIterationStatement(node, true)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23527,7 +24186,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23535,7 +24194,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -23544,22 +24203,22 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~977327425; + return transformFlags & ~647001409; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432; - if (subtreeFlags & 8388608) { + var transformFlags = subtreeFlags | 8388608; + if (subtreeFlags & 2097152) { transformFlags |= 192; } if (node.flags & 3) { - transformFlags |= 192 | 4194304; + transformFlags |= 192 | 1048576; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~948962625; + return transformFlags & ~639894849; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 939525441; + var excludeFlags = 637535553; switch (kind) { case 120: case 199: @@ -23625,7 +24284,7 @@ var ts; transformFlags |= 192; break; case 205: - transformFlags |= 8 | 192 | 16777216; + transformFlags |= 8 | 192 | 4194304; break; case 119: case 134: @@ -23668,60 +24327,60 @@ var ts; excludeFlags = -3; break; case 147: - transformFlags |= 2097152; - if (subtreeFlags & 16384) { - transformFlags |= 65536; + transformFlags |= 524288; + if (subtreeFlags & 8192) { + transformFlags |= 32768; } break; case 206: - transformFlags |= 192 | 524288; + transformFlags |= 192 | 131072; break; case 275: - transformFlags |= 8 | 1048576; + transformFlags |= 8 | 262144; break; case 97: - transformFlags |= 192 | 134217728; + transformFlags |= 192 | 33554432; excludeFlags = 536872257; break; case 99: - transformFlags |= 16384; + transformFlags |= 8192; break; case 182: - transformFlags |= 192 | 8388608; - if (subtreeFlags & 524288) { - transformFlags |= 8 | 1048576; + transformFlags |= 192 | 2097152; + if (subtreeFlags & 131072) { + transformFlags |= 8 | 262144; } - excludeFlags = 940049729; + excludeFlags = 637666625; break; case 183: - transformFlags |= 192 | 8388608; - excludeFlags = 940049729; + transformFlags |= 192 | 2097152; + excludeFlags = 637666625; break; case 184: transformFlags |= 192; if (node.dotDotDotToken) { - transformFlags |= 524288; + transformFlags |= 131072; } break; case 150: transformFlags |= 3 | 4096; break; case 186: - excludeFlags = 942740801; - if (subtreeFlags & 2097152) { + excludeFlags = 638358849; + if (subtreeFlags & 524288) { transformFlags |= 192; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 32768) { + transformFlags |= 8192; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } break; case 185: case 190: - excludeFlags = 940049729; - if (subtreeFlags & 524288) { + excludeFlags = 637666625; + if (subtreeFlags & 131072) { transformFlags |= 192; } break; @@ -23729,21 +24388,21 @@ var ts; case 222: case 223: case 224: - if (subtreeFlags & 4194304) { + if (subtreeFlags & 1048576) { transformFlags |= 192; } break; case 277: - if (subtreeFlags & 32768) { + if (subtreeFlags & 16384) { transformFlags |= 192; } break; case 228: - transformFlags |= 33554432 | 8; + transformFlags |= 8388608 | 8; break; case 226: case 227: - transformFlags |= 33554432; + transformFlags |= 8388608; break; } node.transformFlags = transformFlags | 536870912; @@ -23757,27 +24416,27 @@ var ts; case 189: case 190: case 185: - return 940049729; + return 637666625; case 242: - return 977327425; + return 647001409; case 149: - return 939525441; + return 637535553; case 195: - return 1003902273; + return 653604161; case 194: case 237: - return 1003935041; + return 653620545; case 236: - return 948962625; + return 639894849; case 238: case 207: - return 942011713; + return 638121281; case 155: - return 1003668801; + return 653616449; case 154: case 156: case 157: - return 1003668801; + return 653616449; case 119: case 134: case 131: @@ -23796,12 +24455,12 @@ var ts; case 240: return -3; case 186: - return 942740801; + return 638358849; case 272: - return 940574017; + return 637797697; case 182: case 183: - return 940049729; + return 637666625; case 192: case 210: case 306: @@ -23810,9 +24469,9 @@ var ts; return 536872257; case 187: case 188: - return 671089985; + return 570426689; default: - return 939525441; + return 637535553; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -24013,6 +24672,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); var cancellationToken; var requestedExternalEmitHelpers; var externalHelpersModule; @@ -24022,7 +24693,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -24031,6 +24703,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -24230,8 +24903,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -24295,7 +24968,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -24325,8 +24999,19 @@ var ts; var stringType = createIntrinsicType(4, "string"); var numberType = createIntrinsicType(8, "number"); var falseType = createIntrinsicType(256, "false"); + var regularFalseType = createIntrinsicType(256, "false"); var trueType = createIntrinsicType(256, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256, "true"); + falseType.flags |= 33554432; + trueType.flags |= 33554432; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024, "symbol"); var voidType = createIntrinsicType(4096, "void"); var neverType = createIntrinsicType(32768, "never"); @@ -24364,6 +25049,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -24379,6 +25066,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -24390,7 +25078,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); var flowLoopStart = 0; var flowLoopCount = 0; @@ -24546,35 +25233,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2) - result |= 67216319; + result |= 67220415; if (flags & 1) - result |= 67216318; + result |= 67220414; if (flags & 4) result |= 0; if (flags & 8) result |= 68008959; if (flags & 16) - result |= 67215791; + result |= 67219887; if (flags & 32) result |= 68008383; if (flags & 64) - result |= 67901832; + result |= 67897736; if (flags & 256) result |= 68008191; if (flags & 128) result |= 68008831; if (flags & 512) - result |= 67215503; + result |= 110735; if (flags & 8192) - result |= 67208127; + result |= 67212223; if (flags & 32768) - result |= 67150783; + result |= 67154879; if (flags & 65536) - result |= 67183551; + result |= 67187647; if (flags & 262144) - result |= 67639784; + result |= 67635688; if (flags & 524288) - result |= 67901928; + result |= 67897832; if (flags & 2097152) result |= 2097152; return result; @@ -24614,6 +25301,7 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { target.valueDeclaration = source.valueDeclaration; } @@ -24635,52 +25323,53 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 || source.flags & 384); - var isEitherBlockScoped = !!(target.flags & 2 || source.flags & 2); + var isEitherBlockScoped_1 = !!(target.flags & 2 || source.flags & 2); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -24772,8 +25461,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -24880,18 +25569,25 @@ var ts; if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 67901928 && lastLocation.kind !== 289) { + if (meaning & result.flags & 67897832 && lastLocation.kind !== 289) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 149 || lastLocation.kind === 148 : false; } - if (meaning & 67216319 && result.flags & 1) { - useResult = - lastLocation.kind === 149 || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3) { + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1) { + useResult = + lastLocation.kind === 149 || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173) { @@ -24946,7 +25642,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319)) { + if (lookup(ctor.locals, name, meaning & 67220415)) { propertyWithInvalidInitializer = location; } } @@ -24955,7 +25651,7 @@ var ts; case 238: case 207: case 239: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928)) { + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -24977,7 +25673,7 @@ var ts; case 209: if (lastLocation === location.expression && location.parent.token === 85) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -24988,7 +25684,7 @@ var ts; case 147: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239) { - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -25044,7 +25740,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -25053,7 +25749,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, false)) { return requireSymbol; } @@ -25094,13 +25790,13 @@ var ts; } if (errorLocation && (meaning & 2 || - ((meaning & 32 || meaning & 384) && (meaning & 67216319) === 67216319))) { + ((meaning & 32 || meaning & 384) && (meaning & 67220415) === 67220415))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule && (meaning & 67216319) === 67216319 && !(originalLocation.flags & 2097152)) { + if (result && isInExternalModule && (meaning & 67220415) === 67220415 && !(originalLocation.flags & 2097152)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); @@ -25188,9 +25884,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(errorLocation) ? 67216319 : 0); + var namespaceMeaning = 1920 | (ts.isInJSFile(errorLocation) ? 67220415 : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~namespaceMeaning, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~namespaceMeaning, undefined, undefined, false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -25209,29 +25905,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 & ~1024)) { + if (meaning & (67220415 & ~1024)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~67216319, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~67220415, undefined, undefined, false)); if (symbol && !(symbol.flags & 1024)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 & ~1024 & ~67901928)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67216319, undefined, undefined, false)); + if (meaning & (67220415 & ~1024 & ~67897832)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67220415, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 & ~1024 & ~67216319)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67901928, undefined, undefined, false)); + else if (meaning & (67897832 & ~1024 & ~67220415)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67897832, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -25241,7 +25940,7 @@ var ts; } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -25258,6 +25957,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -25313,7 +26015,7 @@ var ts; } return true; } - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); @@ -25347,7 +26049,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 | 1920)) { + if (valueSymbol.flags & (67897832 | 1920)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -25400,7 +26102,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -25434,7 +26136,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 | 67901928 | 1920, true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 | 67897832 | 1920, true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -25453,7 +26155,7 @@ var ts; case 251: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255: - return getTargetOfExportSpecifier(node, 67216319 | 67901928 | 1920, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 | 67897832 | 1920, dontRecursivelyResolve); case 252: case 202: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -25464,7 +26166,7 @@ var ts; } } function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 | 67901928 | 1920; } + if (excludes === void 0) { excludes = 67220415 | 67897832 | 1920; } if (!symbol) return false; return (symbol.flags & (2097152 | excludes)) === 2097152 || !!(symbol.flags & 2097152 && symbol.flags & 67108864); @@ -25498,7 +26200,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -25531,21 +26233,21 @@ var ts; } else { ts.Debug.assert(entityName.parent.kind === 246); - return resolveEntityName(entityName, 67216319 | 67901928 | 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 | 67897832 | 1920, false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, undefined, 16 | 4); } function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(name) ? meaning & 67216319 : 0); + var namespaceMeaning = 1920 | (ts.isInJSFile(name) ? meaning & 67220415 : 0); var symbol; if (name.kind === 71) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true); if (!symbol) { return symbolFromJSPrototype; @@ -25561,7 +26263,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -25590,15 +26292,15 @@ var ts; ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, undefined, name, true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -25606,9 +26308,19 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3) { + ts.getAssignmentDeclarationKind(host.expression) === 3) { var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6) { + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -25616,6 +26328,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -25645,7 +26364,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(false, errorNode, resolvedModule, moduleReference); } return getMergedSymbol(sourceFile.symbol); @@ -25661,7 +26380,7 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -25691,7 +26410,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -25699,7 +26418,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json") && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -25711,23 +26430,21 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages(undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages(undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -25937,7 +26654,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67216319); + return !!(symbol.flags & 67220415 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67220415); } function findConstructorDeclaration(node) { var members = node.members; @@ -26030,7 +26747,7 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 67216319 ? 67216319 : 1920; + return rightMeaning === 67220415 ? 67220415 : 1920; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -26069,7 +26786,8 @@ var ts; && symbolFromSymbolTable.escapedName !== "export=" && symbolFromSymbolTable.escapedName !== "default" && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -26126,11 +26844,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832, false); return access.accessibility === 0; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415, false); return access.accessibility === 0; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -26154,7 +26872,14 @@ var ts; }; } } - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -26242,14 +26967,14 @@ var ts; if (entityName.parent.kind === 165 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147) { - meaning = 67216319 | 1048576; + meaning = 67220415 | 1048576; } else if (entityName.kind === 146 || entityName.kind === 187 || entityName.parent.kind === 246) { meaning = 1920; } else { - meaning = 67901928; + meaning = 67897832; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); @@ -26271,6 +26996,9 @@ var ts; if (flags & 8) { nodeFlags |= 16384; } + if (flags & 16) { + nodeFlags |= 67108864; + } var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -26353,7 +27081,11 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -26398,13 +27130,13 @@ var ts; } if (type.flags & 512 && !(type.flags & 262144)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928, false); + var parentName = symbolToName(parentSymbol, context, 67897832, false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, undefined); } if (type.flags & 544) { - var name = symbolToName(type.symbol, context, 67901928, false); + var name = symbolToName(type.symbol, context, 67897832, false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, undefined); } @@ -26424,7 +27156,7 @@ var ts; if (!(context.flags & 1048576)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319); + return symbolToTypeNode(type.symbol, context, 67220415); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -26490,17 +27222,20 @@ var ts; return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 | 8), undefined); } return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928) + ? symbolToTypeNode(type.symbol, context, 67897832) : ts.createTypeReferenceNode(ts.createIdentifier("?"), undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832, typeArgumentNodes); } if (type.flags & (262144 | 524288)) { var types = type.flags & 262144 ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 ? 171 : 172, typeNodes); @@ -26567,19 +27302,19 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 : 67216319; + if (isJSConstructor(symbol.valueDeclaration)) { + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 : 67220415; return symbolToTypeNode(symbol, context, isInstanceType); } else if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319); + return symbolToTypeNode(symbol, context, 67220415); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - return symbolToTypeNode(typeAlias, context, 67901928); + return symbolToTypeNode(typeAlias, context, 67897832); } else { context.approximateLength += 3; @@ -26657,8 +27392,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -26694,7 +27429,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16; - var ref = symbolToTypeNode(parent, context, 67901928, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -26707,7 +27442,7 @@ var ts; } var flags = context.flags; context.flags |= 16; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -26801,17 +27536,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 | 1048576, undefined, undefined, true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319, true); + var propertyName = symbolToName(propertySymbol, context, 67220415, true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; @@ -26930,7 +27661,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928, undefined, type.symbol.escapedName, false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832, undefined, type.symbol.escapedName, false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -26941,7 +27672,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8) - : symbolToName(type.symbol, context, 67901928, true); + : symbolToName(type.symbol, context, 67897832, true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -26980,6 +27711,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184) { @@ -26989,11 +27723,20 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 | 1048576, undefined, undefined, true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64) && !(context.flags & 67108864)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, true)); ts.Debug.assert(chain && chain.length > 0); } @@ -27089,7 +27832,10 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -27097,7 +27843,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384)); - var isTypeOf = meaning === 67216319; + var isTypeOf = meaning === 67220415; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); @@ -27194,6 +27940,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216; } @@ -27252,7 +28001,7 @@ var ts; var baseType = t.flags & 256 ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -27411,10 +28160,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252) { - exportSymbol = resolveName(node, node.escapedText, 67216319 | 67901928 | 1920 | 2097152, undefined, node, false); + exportSymbol = resolveName(node, node.escapedText, 67220415 | 67897832 | 1920 | 2097152, undefined, node, false); } else if (node.parent.kind === 255) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 | 67901928 | 1920 | 2097152); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 | 67897832 | 1920 | 2097152); } var result; if (exportSymbol) { @@ -27434,7 +28183,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 | 67901928 | 1920, undefined, undefined, false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 | 67897832 | 1920, undefined, undefined, false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -27471,6 +28220,8 @@ var ts; switch (propertyName) { case 0: return !!getSymbolLinks(target).type; + case 5: + return !!(getNodeLinks(target).resolvedEnumType); case 2: return !!getSymbolLinks(target).declaredType; case 1: @@ -27479,6 +28230,8 @@ var ts; return !!target.resolvedReturnType; case 4: return !!target.immediateBaseConstraint; + case 6: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -27622,33 +28375,33 @@ var ts; } else { var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } } } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192)) { type = getTypeWithFacts(type, 131072); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -27688,7 +28441,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1) && !(declaration.flags & 4194304)) { if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { @@ -27712,15 +28465,21 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } var type = declaration.symbol.escapedName === "this" ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } if (declaration.initializer) { @@ -27735,15 +28494,15 @@ var ts; } return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -27757,8 +28516,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -27766,16 +28525,16 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; if (!type) { var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -27786,15 +28545,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -27813,7 +28570,7 @@ var ts; type.objectFlags |= 16384; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -27826,10 +28583,10 @@ var ts; } return declaredType; } - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 && - special === 2 && + kind === 2 && symbol.escapedName === "export=") { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -27853,9 +28610,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -27875,8 +28630,8 @@ var ts; return expression && isDeclarationInConstructor(expression); }); } - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, false).parent; return ts.isClassLike(parent) && parent; }); @@ -27884,7 +28639,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -27895,8 +28650,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -27966,9 +28721,9 @@ var ts; return getWidenedType(type); } type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -28007,18 +28762,25 @@ var ts; } if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } if (!pushTypeResolution(symbol, 0)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -28031,7 +28793,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -28092,7 +28854,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156); var setter = ts.getDeclarationOfKind(symbol, 157); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -28116,14 +28878,12 @@ var ts; type = getReturnTypeFromBody(getter); } else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -28146,7 +28906,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -28173,7 +28933,7 @@ var ts; } else if (declaration.kind === 202 || declaration.kind === 187 && declaration.parent.kind === 202) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -28182,11 +28942,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=")); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16, symbol); @@ -28206,7 +28966,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 67216319 + links.type = targetSymbol.flags & 67220415 ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -28215,22 +28975,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -28375,23 +29127,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -28452,7 +29201,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); @@ -28460,8 +29211,8 @@ var ts; else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); @@ -28542,7 +29293,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928, true); + var baseSymbol = resolveEntityName(node.expression, 67897832, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -28671,9 +29422,9 @@ var ts; if (declaration.kind === 241) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -28851,7 +29602,7 @@ var ts; if (type.flags & 2048) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192) { + if (type.flags & (64 | 128)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -28866,7 +29617,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319) { + if (symbolFlags & 67220415) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -29067,7 +29818,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, false, false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -29190,7 +29941,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { var signatures = getSignaturesOfType(t, 1); @@ -29208,7 +29959,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -29254,6 +30005,7 @@ var ts; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); if (symbol.flags & (16 | 8192)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); @@ -29348,7 +30100,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -29505,10 +30257,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -29520,7 +30277,8 @@ var ts; } function getConstraintOfDistributiveConditionalType(type) { if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -29582,6 +30340,7 @@ var ts; return getResolvedBaseConstraint(type) !== circularConstraintType; } function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -29589,8 +30348,14 @@ var ts; if (!pushTypeResolution(t, 4)) { return circularConstraintType; } + if (constraintDepth === 50) { + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -29612,8 +30377,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -29628,7 +30393,7 @@ var ts; if (t.flags & 2097152) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304) { @@ -29638,9 +30403,6 @@ var ts; if (t.flags & 8388608) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -29677,16 +30439,31 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } function getApparentType(type) { var t = type.flags & 15794176 ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 ? globalStringType : - t.flags & 168 ? globalNumberType : - t.flags & 272 ? globalBooleanType : - t.flags & 3072 ? getGlobalESSymbolType(languageVersion >= 2) : - t.flags & 16777216 ? emptyObjectType : - t.flags & 1048576 ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 ? getApparentTypeOfMappedType(t) : + t.flags & 524288 ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 ? globalStringType : + t.flags & 168 ? globalNumberType : + t.flags & 272 ? globalBooleanType : + t.flags & 3072 ? getGlobalESSymbolType(languageVersion >= 2) : + t.flags & 16777216 ? emptyObjectType : + t.flags & 1048576 ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -29715,10 +30492,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1)) || getIndexInfoOfType(type, 0)); - if (index) { - checkFlags |= index.isReadonly ? 8 : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1) || getIndexInfoOfType(type, 0)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16; @@ -29795,8 +30572,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -29867,7 +30648,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && (node.type && node.type.kind === 286 + return ts.isInJSFile(node) && (node.type && node.type.kind === 286 || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; return isBracketed || !!typeExpression && typeExpression.type.kind === 286; @@ -29957,7 +30738,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -29966,7 +30747,7 @@ var ts; var paramSymbol = param.symbol; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319, undefined, undefined, false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415, undefined, undefined, false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -30001,7 +30782,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, undefined, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; @@ -30024,7 +30805,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -30108,7 +30889,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -30149,6 +30930,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -30185,7 +30967,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -30204,8 +30986,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -30239,7 +31025,7 @@ var ts; signature; } function createCanonicalSignature(signature) { - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -30409,10 +31195,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -30438,7 +31224,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -30485,32 +31271,50 @@ var ts; if (type) { return type; } + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); if (jsdocType) { return jsdocType; } - resolveTypeReferenceName(getTypeReferenceName(node), 67901928); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832); return getTypeOfSymbol(symbol); } function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType || assignedType) { - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + if (referenceType || assignedType) { + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -30626,10 +31430,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928; + var meaning = 67897832; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319; + meaning |= 67220415; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -30678,10 +31482,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name, false); @@ -30708,6 +31512,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -30734,7 +31541,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928, undefined); + var symbol = getGlobalSymbol(name, 67897832, undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -30845,6 +31652,13 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -30901,10 +31715,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -30917,15 +31728,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -30971,7 +31773,7 @@ var ts; var remove = t.flags & 64 && includes & 4 || t.flags & 128 && includes & 8 || t.flags & 2048 && includes & 1024 || - t.flags & 192 && t.flags & 33554432 && containsType(types, t.regularType); + t.flags & 448 && t.flags & 33554432 && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -30992,7 +31794,7 @@ var ts; } switch (unionReduction) { case 1: - if (includes & 2240) { + if (includes & 2240 | 256) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -31080,18 +31882,15 @@ var ts; if (type === wildcardType) includes |= 268435456; } - else if ((strictNullChecks || !(flags & 24576)) && !ts.contains(typeSet, type) && - !(flags & 131072 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } return includes; } function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -31308,7 +32107,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? @@ -31321,20 +32120,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 99); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576) && isTypeAssignableToKind(indexType, 68 | 168 | 3072)) { @@ -31380,7 +32182,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -31398,7 +32200,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 | 134217728); @@ -31406,18 +32211,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 | 1048576); } - function isStringIndexOnlyType(type) { - if (type.flags & 131072 && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 ? getSimplifiedIndexedAccessType(type) : type; } @@ -31427,27 +32220,16 @@ var ts; } type.simplified = circularConstraintType; var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 && isGenericObjectType(objectType)) { - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + if (indexType.flags & 262144) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + if (!(indexType.flags & 15794176)) { + if (objectType.flags & 262144) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + if (objectType.flags & 524288) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } if (isGenericMappedType(objectType)) { @@ -31466,7 +32248,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -31484,17 +32267,26 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 && !(indexType.flags & 16)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false, missingType); + if (propType === missingType) { + if (!accessNode) { + return missingType; + } + else { + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -31653,7 +32445,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 : node.flags & 2097152 ? 67216319 | 67901928 : 67901928; + var targetMeaning = node.isTypeOf ? 67220415 : node.flags & 2097152 ? 67220415 | 67897832 : 67897832; var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; @@ -31682,7 +32474,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 + var errorMessage = targetMeaning === 67220415 ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -31696,7 +32488,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319) { + if (meaning === 67220415) { return links.resolvedType = getTypeOfSymbol(symbol); } else { @@ -31830,7 +32622,7 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 && !(type.flags & 33554432)) { + if (type.flags & 448 && !(type.flags & 33554432)) { if (!type.freshType) { var freshType = createLiteralType(type.flags | 33554432, type.value, type.symbol); freshType.regularType = type; @@ -31841,7 +32633,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 && type.flags & 33554432 ? type.regularType : + return type.flags & 448 && type.flags & 33554432 ? type.regularType : type.flags & 262144 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -32037,7 +32829,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -32119,7 +32911,7 @@ var ts; var typeParameters = links.outerTypeParameters; if (!typeParameters) { var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -32129,7 +32921,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -32182,31 +32974,41 @@ var ts; return !!ts.forEachChild(node, containsReference); } } - function instantiateMappedType(type, mapper) { + function getHomomorphicTypeVariable(type) { var constraintType = getConstraintTypeFromMappedType(type); if (constraintType.flags & 1048576) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536) { + return typeVariable; + } + } + return undefined; + } + function instantiateMappedType(type, mapper) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 | 14745600 | 131072 | 524288) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 | 14745600 | 131072 | 524288); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -32230,6 +33032,11 @@ var ts; var result = createObjectType(type.objectFlags | 64, type.symbol); if (type.objectFlags & 32) { result.declaration = type.declaration; + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -32263,46 +33070,59 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536) { + return mapper(type); + } + if (flags & 131072) { + var objectFlags = type.objectFlags; + if (objectFlags & 16) { + return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072) { - if (type.objectFlags & 16) { - return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 && !(type.flags & 32764)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 && !(flags & 32764)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -32367,7 +33187,7 @@ var ts; return body.kind === 216 ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -32406,8 +33226,9 @@ var ts; return source.flags & 262144 ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 | 16777216)) : + target === globalFunctionType ? !!(source.flags & 131072) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } function isTypeComparableTo(source, target) { return isTypeRelatedTo(source, target, comparableRelation); @@ -32419,53 +33240,116 @@ var ts; return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); } function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 || (type.flags & 524288 && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268: case 193: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202: switch (node.operatorToken.kind) { case 58: case 26: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195: + return elaborateArrowFunction(node, source, target, relation); } return false; } - function elaborateElementwise(iterator, source, target) { + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0); + var constructSignatures = getSignaturesOfType(source, 1); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 | 32768)) && checkTypeRelatedTo(returnType, target, relation, undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + if (ts.isBlock(node.body)) { + return false; + } + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, undefined, undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } + } + return false; + } + function elaborateElementwise(iterator, source, target, relation) { var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, undefined); if (elaborated) { reportedError = true; } else { var resultObj = {}; var specificSource = next ? checkExpressionForMutableLocation(next, 0, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, undefined, resultObj); if (result && specificSource !== sourcePropType) { - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -32476,13 +33360,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168) && getIndexInfoOfType(target, 1) || getIndexInfoOfType(target, 0) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -32516,8 +33403,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -32548,9 +33435,13 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + var tupleizedType = checkArrayLiteral(node, 3, true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -32599,8 +33490,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); @@ -32621,9 +33512,9 @@ var ts; source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { return 0; } var kind = target.declaration ? target.declaration.kind : 0; @@ -32645,11 +33536,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && @@ -32666,13 +33557,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); @@ -32828,10 +33719,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 && source.flags & 33554432) { + if (source.flags & 448 && source.flags & 33554432) { source = source.regularType; } - if (target.flags & 192 && target.flags & 33554432) { + if (target.flags & 448 && target.flags & 33554432) { target = target.regularType; } if (source === target || @@ -32946,10 +33837,10 @@ var ts; } function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 && source.flags & 33554432) { + if (source.flags & 448 && source.flags & 33554432) { source = source.regularType; } - if (target.flags & 192 && target.flags & 33554432) { + if (target.flags & 448 && target.flags & 33554432) { target = target.regularType; } if (source.flags & 8388608) { @@ -32991,13 +33882,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432) && - !(target.flags & 262144) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 | 131072 | 524288) && source !== globalObjectType && + target.flags & (131072 | 524288) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0); @@ -33070,7 +33958,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072) { + if (flags & 131072 || flags & 2097152 || flags & 4194304 || flags & 1048576 || flags & 8388608) { return recursiveTypeRelatedTo(source, target, false); } if (flags & (262144 | 524288)) { @@ -33080,32 +33968,6 @@ var ts; } } } - if (flags & 1048576) { - return isRelatedTo(source.type, target.type, false); - } - if (flags & 2097152) { - if (result = isRelatedTo(source.objectType, target.objectType, false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, false)) { - return result; - } - } - } - if (flags & 4194304) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608) { - return isRelatedTo(source.substitute, target.substitute, false); - } return 0; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -33121,8 +33983,8 @@ var ts; if (discriminant) { return hasExcessProperties(source, discriminant, undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { if (!errorNode) return { value: ts.Debug.fail() }; @@ -33154,13 +34016,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1; var sourceTypes = source.types; @@ -33189,7 +34054,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], true); } return 0; @@ -33216,31 +34082,23 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1; @@ -33383,6 +34241,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072)) { + if (flags & 1048576) { + return isRelatedTo(source.type, target.type, false); + } + var result_2 = 0; + if (flags & 2097152) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, false)) { + return result_2; + } + } + } + if (flags & 4194304) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608) { + return isRelatedTo(source.substitute, target.substitute, false); + } + return 0; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -33407,18 +34296,19 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1) { + return -1; } } } } else if (target.flags & 2097152) { - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -33434,7 +34324,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -33502,6 +34391,25 @@ var ts; } } else { + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0; + } + var sourceIsPrimitive = !!(source.flags & 32764); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target && !(ts.getObjectFlags(source) & 8192 || ts.getObjectFlags(target) & 8192)) { var variances = getVariances(source.target); @@ -33516,29 +34424,20 @@ var ts; errorInfo = saveErrorInfo; } } - var sourceIsPrimitive = !!(source.flags & 32764); - if (relation !== identityRelation) { - source = getApparentType(source); + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1) || anyType, getIndexTypeOfType(target, 1) || anyType, reportErrors); } if (source.flags & (131072 | 524288) && target.flags & 131072) { var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); } } } @@ -33558,10 +34457,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0; @@ -33684,29 +34583,6 @@ var ts; } return result; } - function isWeakType(type) { - if (type.flags & 131072) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); - } - if (type.flags & 524288) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 && target.flags & 131072)) { return 0; @@ -33738,8 +34614,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1) ? 0 : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1) ? @@ -33907,6 +34783,48 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + function isWeakType(type) { + if (type.flags & 131072) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); + } + if (type.flags & 524288) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); result.objectFlags |= 8192; @@ -34134,8 +35052,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -34181,9 +35099,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 | 32768)); @@ -34205,10 +35128,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 && type.flags & 33554432 ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 && type.flags & 33554432 ? stringType : type.flags & 128 && type.flags & 33554432 ? numberType : - type.flags & 256 ? booleanType : + type.flags & 256 && type.flags & 33554432 ? booleanType : type.flags & 262144 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -34229,13 +35152,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -34244,7 +35171,7 @@ var ts; return type.flags & 262144 ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 ? type.value === "" ? 64 : 0 : type.flags & 128 ? type.value === 0 ? 128 : 0 : - type.flags & 256 ? type === falseType ? 256 : 0 : + type.flags & 256 ? (type === falseType || type === regularFalseType) ? 256 : 0 : type.flags & 29148; } function removeDefinitelyFalsyTypes(type) { @@ -34258,11 +35185,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 ? emptyStringType : type.flags & 8 ? zeroType : - type.flags & 16 || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 | 8192 | 16384) || - type.flags & 64 && type.value === "" || - type.flags & 128 && type.value === 0 ? type : - neverType; + type.flags & 64 && type.value === "" || + type.flags & 128 && type.value === 0 ? type : + neverType; } function getNullableType(type, flags) { var missing = (flags & ~type.flags) & (8192 | 16384); @@ -34468,8 +35396,11 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + return; + } var diagnostic; switch (declaration.kind) { case 202: @@ -34492,43 +35423,48 @@ var ts; case 157: case 194: case 195: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728) { if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -34686,7 +35622,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -34749,11 +35687,11 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8) && target.flags & 65536 && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -34801,6 +35739,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432) { var targetTypes = target.types; var typeVariableCount = 0; @@ -34831,7 +35772,12 @@ var ts; } else { if (!(priority & 32 && source.flags & (524288 | 15794176))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 | 524288))) { + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 | 524288)) { var key = source.id + "," + target.id; @@ -34914,33 +35860,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -34950,12 +35901,19 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0; + bivariant = bivariant || kind === 154 || kind === 153 || kind === 155; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -34986,8 +35944,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -35006,7 +35964,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 | 1048576); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 | 1048576); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128); @@ -35024,7 +35982,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { var candidates = widenObjectLiteralCandidates(inference.candidates); var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); var widenLiteralTypes = !primitiveConstraint && inference.topLevel && @@ -35032,7 +35990,7 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = context.flags & 1 || inference.priority & 28 ? + var unwidenedType = inference.priority & 28 ? getUnionType(baseCandidates, 2) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -35043,14 +36001,17 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2) { + else if (context.flags & 1) { inferredType = silentNeverType; } else { @@ -35059,7 +36020,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2)); } } } @@ -35087,11 +36048,40 @@ var ts; } return result; } + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 67220415 | 1048576, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -35199,14 +36189,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144) { + if (type.flags & (16 | 512)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 && !(combined & 15794176)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -35250,13 +36256,28 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { if (assignedType.flags & 32768) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 && assignedType.flags & 256) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); + } + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -35264,8 +36285,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -35300,13 +36321,15 @@ var ts; } if (flags & 272) { return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; + (type === falseType || type === regularFalseType) ? 3030404 : 1981828 : + (type === falseType || type === regularFalseType) ? 3145092 : 4193668; } if (flags & 131072) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 : 4181984 : - strictNullChecks ? 1972176 : 4184016; + return ts.getObjectFlags(type) & 16 && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 : 4194303 : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 : 4181984 : + strictNullChecks ? 1972176 : 4184016; } if (flags & (4096 | 8192)) { return 2457472; @@ -35346,7 +36369,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, undefined, false, false) || errorType; } @@ -35429,10 +36452,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 || node.kind === 184 ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 || node.kind === 184 ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 && node.initializer && @@ -35478,6 +36501,21 @@ var ts; } return links.switchTypes; } + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269) { + if (clause.expression.kind === 9) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -35502,6 +36540,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144) { var types = type.types; @@ -35520,8 +36561,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35590,8 +36631,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768)) { if (!(ts.getObjectFlags(t) & 256)) { return false; @@ -35662,7 +36703,7 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { + if (flowDepth === 2000) { flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -35751,15 +36792,21 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } if (containsMatchingReference(reference, node)) { + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 || init.kind === 195)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } return undefined; @@ -35782,7 +36829,7 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -35811,15 +36858,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -36041,9 +37094,19 @@ var ts; if (type.flags & 1 && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 : + typeofNEFacts.get(literal.text) || 8192; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -36054,11 +37117,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 : - typeofNEFacts.get(literal.text) || 8192; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { var switchTypes = getSwitchClauseTypes(switchStatement); @@ -36076,6 +37136,47 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (!(hasDefaultClause || (type.flags & 262144))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -36085,7 +37186,7 @@ var ts; return type; } var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -36100,21 +37201,12 @@ var ts; return type; } if (!targetType) { - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16) { - constructSignatures = getSignaturesOfType(rightType, 1); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -36218,8 +37310,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304)) { - links.flags |= 4194304; + if (!(links.flags & 8388608)) { + links.flags |= 8388608; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -36227,7 +37319,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608); }); } function markParameterAssignments(node) { if (node.kind === 71) { @@ -36270,7 +37362,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, 67216319) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, 67220415) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -36303,8 +37395,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; + getNodeLinks(declaration).flags |= 16777216; + getNodeLinks(node).flags |= 33554432; break; } container = ts.getContainingClass(container); @@ -36315,8 +37407,8 @@ var ts; while (container.kind !== 277) { if (container.parent === declaration) { if (container.kind === 152 && ts.hasModifier(container, 32)) { - getNodeLinks(declaration).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; + getNodeLinks(declaration).flags |= 16777216; + getNodeLinks(node).flags |= 33554432; } break; } @@ -36329,7 +37421,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -36392,6 +37484,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || @@ -36411,19 +37506,39 @@ var ts; } if (containedInIterationStatement) { if (usedInFunction) { - getNodeLinks(current).flags |= 65536; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536; + } } if (container.kind === 223 && ts.getAncestor(symbol.valueDeclaration, 236).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304; } - getNodeLinks(symbol.valueDeclaration).flags |= 262144; + getNodeLinks(symbol.valueDeclaration).flags |= 524288; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072; + getNodeLinks(symbol.valueDeclaration).flags |= 262144; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { var current = node; while (current.parent.kind === 193) { @@ -36530,23 +37645,23 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - if (container.kind === 194 && - container.parent.kind === 202 && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { - var className = container.parent - .left - .expression - .expression; + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } - else if ((container.kind === 194 || container.kind === 237) && + else if (isInJS && + (container.kind === 194 || container.kind === 237) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -36561,13 +37676,36 @@ var ts; var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + if (container.kind === 194 && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3) { + return container.parent + .left + .expression + .expression; + } + else if (container.kind === 154 && + container.parent.kind === 186 && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6) { + return container.parent.parent.left.expression; + } + else if (container.kind === 194 && + container.parent.kind === 273 && + container.parent.parent.kind === 186 && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287) { @@ -36718,7 +37856,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -36765,7 +37903,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -36824,9 +37962,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) - : contextualReturnType; + if (contextualReturnType) { + if (functionFlags & 2) { + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -36887,10 +38037,17 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54: var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53: case 26: @@ -36899,8 +38056,8 @@ var ts; return undefined; } } - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0: return true; @@ -36916,19 +38073,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319, undefined, id.escapedText, true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415, undefined, id.escapedText, true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4: case 2: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -36946,6 +38130,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1) || + getIndexTypeOfContextualType(type, 0); } return undefined; }, true); @@ -36953,9 +38139,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, true); } - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); if (node.flags & 8388608) { @@ -36968,8 +38151,8 @@ var ts; var type = getApparentTypeOfContextualType(objectLiteral); if (type) { if (!hasNonBindableDynamicName(element)) { - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -37022,44 +38205,34 @@ var ts; case 86: case 95: case 71: + case 140: return true; case 187: case 193: return isPossiblyDiscriminantValue(node.expression); + case 268: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } function getContextualType(node) { if (node.flags & 8388608) { @@ -37081,6 +38254,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205: return getContextualTypeForYieldOperand(parent); + case 199: + return getContextualTypeForAwaitOperand(parent); case 189: case 190: return getContextualTypeForArgument(parent, node); @@ -37105,7 +38280,7 @@ var ts; ts.Debug.assert(parent.parent.kind === 204); return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193: { - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268: @@ -37124,6 +38299,9 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -37131,7 +38309,7 @@ var ts; if (isTypeAny(valueType)) { return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -37195,11 +38373,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -37290,8 +38468,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -37323,7 +38501,7 @@ var ts; return (node.kind === 184 && !!node.initializer) || (node.kind === 202 && node.operatorToken.kind === 58); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -37333,7 +38511,7 @@ var ts; for (var index = 0; index < elementCount; index++) { var e = elements[index]; if (inDestructuringPattern && e.kind === 206) { - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1) || getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); if (restElementType) { @@ -37342,7 +38520,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206) { @@ -37352,33 +38530,44 @@ var ts; if (!hasNonEndingSpreadElement) { var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206; var minLength = elementCount - (hasRestElement ? 1 : 0); + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - if (!hasRestElement && pattern && (pattern.kind === 183 || pattern.kind === 185)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 && e.dotDotDotToken || e.kind === 206)) { - if (e.kind !== 208) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + if (!hasRestElement && pattern && (pattern.kind === 183 || pattern.kind === 185)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 && e.dotDotDotToken || e.kind === 206)) { + if (e.kind !== 208) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1; } return createArrayType(elementTypes.length ? @@ -37442,9 +38631,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 || contextualType.pattern.kind === 186); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -37462,7 +38651,7 @@ var ts; var type = memberDecl.kind === 273 ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -37643,12 +38832,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096); var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -37665,7 +38856,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -37673,7 +38864,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 0, 4096); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -37682,7 +38873,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096); } } var parent = openingLikeElement.parent.kind === 258 ? openingLikeElement.parent : undefined; @@ -37692,13 +38883,15 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); var childrenPropSymbol = createSymbol(4 | 33554432, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, propagatingFlags, 4096); } } if (hasSpreadAnyType) { @@ -37710,7 +38903,7 @@ var ts; return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); - result.flags |= 268435456; + result.flags |= (propagatingFlags |= 268435456); result.objectFlags |= 128 | 4096; return result; } @@ -37736,7 +38929,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928); + var typeSymbol = exports && getSymbol(exports, name, 67897832); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } function getIntrinsicTagSymbol(node) { @@ -37775,7 +38968,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -37785,7 +38978,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 4 : 0); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 2 : 0); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -37842,7 +39035,7 @@ var ts; return getGlobalSymbol(JsxNames.JSX, 1920, undefined); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832); var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); if (propertiesOfJsxElementAttribPropInterface) { @@ -37859,7 +39052,7 @@ var ts; return undefined; } function getJsxLibraryManagedAttributes(jsxNamespace) { - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832); } function getJsxElementPropertiesName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); @@ -38016,7 +39209,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, true); })); } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { @@ -38098,7 +39291,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319, reactRefErr, reactNamespace, true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = 67108863; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { @@ -38179,10 +39372,10 @@ var ts; if (symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3; + ts.getAssignmentDeclarationKind(parent) === 3; } } function checkPropertyAccessibility(node, isSuper, type, prop) { @@ -38206,7 +39399,7 @@ var ts; } if ((flags & 128) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); return false; } @@ -38342,6 +39535,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192) && getFalsyFlags(flowType) & 8192) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); @@ -38449,7 +39648,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -38534,7 +39733,7 @@ var ts; } var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) - : ts.isInJavaScriptFile(node) && (type.flags & 262144) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } function getForInVariableSymbol(node) { var initializer = node.initializer; @@ -38590,7 +39789,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -38598,7 +39797,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -38696,12 +39895,11 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; - var callIsIncomplete = false; - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { return true; } + var argCount; + var callIsIncomplete = false; if (node.kind === 191) { argCount = args.length; if (node.template.kind === 204) { @@ -38715,7 +39913,7 @@ var ts; } } else if (node.kind === 150) { - argCount = getEffectiveArgumentCount(node, undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -38724,10 +39922,10 @@ var ts; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { return false; @@ -38752,7 +39950,7 @@ var ts; return undefined; } function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { inferTypes(context.inferences, source, target); @@ -38760,7 +39958,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { var skipContextParamType = getTypeAtPosition(signature, 0); @@ -38796,43 +39994,36 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 208) { + var arg = args[i]; + if (arg.kind !== 208) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - if (argType === undefined) { - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 | 15794176) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { return arg.kind === 213 ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1) || anyType; @@ -38840,12 +40031,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -38854,23 +40042,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -38907,28 +40095,24 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 208) { - if (i === restIndex && (restType.flags & 65536 || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } function getThisArgumentOfCall(node) { @@ -38939,10 +40123,17 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } function getEffectiveCallArguments(node) { if (node.kind === 191) { var template = node.template; - var args_4 = [undefined]; + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -38950,178 +40141,70 @@ var ts; } return args_4; } - else if (node.kind === 150) { - return undefined; + if (node.kind === 150) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150) { - switch (node.parent.kind) { - case 238: - case 207: - return 1; - case 152: - return 2; - case 154: - case 156: - case 157: - if (languageVersion === 0) { - return 2; - } - return signature.parameters.length >= 3 ? 3 : 2; - case 149: - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } - function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 238) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238: + case 207: + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149: + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152: + case 154: + case 156: + case 157: + var hasPropDesc = parent.kind !== 152 && languageVersion !== 0; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149) { - node = node.parent; - if (node.kind === 155) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 || - node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } - function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 238) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149) { - node = node.parent; - if (node.kind === 155) { - return anyType; - } - } - if (node.kind === 152 || - node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - var element = node; - var name = element.name; - switch (name.kind) { - case 71: - return getLiteralType(ts.idText(name)); - case 8: - case 9: - return getLiteralType(name.text); - case 147: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 238) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149) { - return numberType; - } - if (node.kind === 152) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - function getEffectiveArgumentType(node, argIndex) { - if (node.kind === 150) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191) { - return getGlobalTemplateStringsArrayType(); - } - return undefined; - } - function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 150 || - (argIndex === 0 && node.kind === 191)) { - return undefined; - } - return args[argIndex]; - } - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150) { - return node.expression; - } - else if (argIndex === 0 && node.kind === 191) { - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238: + case 207: + return 1; + case 152: + return 2; + case 154: + case 156: + case 157: + return languageVersion === 0 || signature.parameters.length <= 2 ? 2 : 3; + case 149: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -39130,6 +40213,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -39138,7 +40222,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -39149,16 +40236,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -39190,19 +40286,7 @@ var ts; } var args = getEffectiveCallArguments(node); var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; var candidateForArgumentError; var candidateForArgumentArityError; var candidateForTypeArgumentError; @@ -39229,14 +40313,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -39256,58 +40343,71 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) { + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) { + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { ts.Debug.assert(candidates.length > 0); return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) @@ -39322,7 +40422,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -39333,7 +40433,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -39360,17 +40460,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -39416,23 +40526,30 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { if (funcType !== errorType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); } if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0, relatedInformation); } return resolveErrorCall(node); } - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -39478,11 +40595,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -39549,10 +40668,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -39573,8 +40693,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -39607,8 +40727,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -39631,7 +40751,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { @@ -39681,32 +40801,36 @@ var ts; links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { if (ts.getJSDocClassTag(node)) return true; - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -39719,14 +40843,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -39769,7 +40890,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -39779,7 +40900,7 @@ var ts; return anyType; } } - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -39787,8 +40908,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -39813,7 +40934,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319, undefined, undefined, false); + return globalESSymbol === resolveName(left, "Symbol", 67220415, undefined, undefined, false); } function checkImportCallExpression(node) { if (!checkGrammarArguments(node.arguments)) @@ -39868,7 +40989,7 @@ var ts; } if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319, undefined, undefined, true); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415, undefined, undefined, true); if (resolvedRequire === requireSymbol) { return true; } @@ -39991,14 +41112,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -40007,17 +41125,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -40041,15 +41149,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -40057,6 +41156,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -40136,6 +41246,14 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + var globalPromiseLikeType = getGlobalPromiseLikeType(true); + if (globalPromiseLikeType !== emptyGenericType) { + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -40242,10 +41360,40 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0; + if (hasDefault) { + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192; + } + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192; + } + } + else { + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64; + } + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197) { + var operandType = getTypeOfExpression(node.expression.expression); + var witnesses = getSwitchClauseTypeOfWitnesses(node); + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -40290,7 +41438,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; @@ -40341,6 +41489,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); if (checkMode === 1 && isContextSensitive(node)) { if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { var links_1 = getNodeLinks(node); @@ -40348,8 +41497,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -40385,7 +41536,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -40562,8 +41712,8 @@ var ts; } if (type.flags & 786432) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40708,7 +41858,7 @@ var ts; if (element.kind !== 206) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -40732,8 +41882,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -40834,7 +41984,7 @@ var ts; return (target.flags & 24576) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -40963,9 +42113,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2) : leftType; case 58: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -40980,15 +42130,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928, undefined, name, false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832, undefined, name, false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -41033,8 +42183,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2: return true; case 1: @@ -41043,7 +42193,7 @@ var ts; case 3: case 4: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -41135,7 +42285,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266) { + if (node.kind === 266 && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; } return node; @@ -41174,19 +42324,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, true); var widened = ts.getCombinedNodeFlags(declaration) & 2 || - (ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -41212,11 +42358,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -41250,29 +42396,37 @@ var ts; return type; } function getTypeOfExpression(node, cache) { - if (node.kind === 189 && node.expression.kind !== 97 && !ts.isRequireCall(node, true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + var expr = ts.skipParentheses(node); + if (expr.kind === 189 && expr.expression.kind !== 97 && !ts.isRequireCall(expr, true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 || expr.kind === 210) { + return getTypeFromTypeNode(expr.type); + } return cache ? checkExpressionCached(node) : checkExpression(node); } function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1); node.contextualType = saveContextualType; return type; } - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -41287,13 +42441,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71: return checkIdentifier(node); @@ -41318,7 +42472,7 @@ var ts; case 12: return globalRegExpType; case 185: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186: return checkObjectLiteral(node, checkMode); case 187: @@ -41408,9 +42562,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); @@ -41434,7 +42585,7 @@ var ts; error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } } - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -41835,7 +42986,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -41866,7 +43017,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -41963,8 +43114,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -42250,10 +43401,10 @@ var ts; case 246: case 249: case 248: - var result_3 = 0; + var result_4 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235: case 184: case 237: @@ -42374,7 +43525,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319, true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415, true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { @@ -42394,7 +43545,7 @@ var ts; return; } var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -42444,7 +43595,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 ? 67901928 : 1920) | 2097152; + var meaning = (typeName.kind === 71 ? 67897832 : 1920) | 2097152; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol && rootSymbol.flags & 2097152 @@ -42662,14 +43813,14 @@ var ts; checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 && ts.nodeIsPresent(body)) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -43091,7 +44242,7 @@ var ts; return visit(n.expression); } else if (n.kind === 71) { - var symbol = resolveName(n, n.escapedText, 67216319 | 2097152, undefined, undefined, false); + var symbol = resolveName(n, n.escapedText, 67220415 | 2097152, undefined, undefined, false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -43158,7 +44309,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); markPropertyAsReferenced(property, undefined, false); - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97, parentType, property); } } @@ -43192,7 +44343,7 @@ var ts; if (node === symbol.valueDeclaration) { var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -43481,11 +44632,15 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } if (isReferenceToType(type, getGlobalIterableType(false)) || isReferenceToType(type, getGlobalIterableIteratorType(false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -43508,9 +44663,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -43965,13 +45122,15 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 2162688)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -44013,7 +45172,7 @@ var ts; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -44031,7 +45190,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -44168,6 +45327,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192); @@ -44604,8 +45765,8 @@ var ts; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { - var excludedMeanings = (symbol.flags & (67216319 | 1048576) ? 67216319 : 0) | - (symbol.flags & 67901928 ? 67901928 : 0) | + var excludedMeanings = (symbol.flags & (67220415 | 1048576) ? 67220415 : 0) | + (symbol.flags & 67897832 ? 67897832 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 ? @@ -44615,7 +45776,7 @@ var ts; } if (compilerOptions.isolatedModules && node.kind === 255 - && !(target.flags & 67216319) + && !(target.flags & 67220415) && !(node.flags & 4194304)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -44666,13 +45827,13 @@ var ts; if (node.moduleReference.kind !== 257) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319) { + if (target.flags & 67220415) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 | 1920).flags & 1920)) { + if (!(resolveEntityName(moduleName, 67220415 | 1920).flags & 1920)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928) { + if (target.flags & 67897832) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -44721,12 +45882,12 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 | 67901928 | 1920 | 2097152, undefined, undefined, true); + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 | 67897832 | 1920 | 2097152, undefined, undefined, true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } @@ -44754,7 +45915,7 @@ var ts; } if (node.expression.kind === 71) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, true); } } @@ -44784,7 +45945,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -44826,7 +45987,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -44990,7 +46151,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -45042,13 +46203,20 @@ var ts; return addOptionality(type); } function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194: case 195: @@ -45100,9 +46268,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -45113,7 +46280,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -45195,7 +46361,7 @@ var ts; case 238: case 239: if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832); } break; case 194: @@ -45269,12 +46435,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -45299,7 +46465,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1: case 3: @@ -45325,7 +46491,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 && entityName.parent === entityName.parent.parent.left) { var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -45334,7 +46500,7 @@ var ts; } } if (entityName.parent.kind === 252 && ts.isEntityNameExpression(entityName)) { - var success = resolveEntityName(entityName, 67216319 | 67901928 | 1920 | 2097152, true); + var success = resolveEntityName(entityName, 67220415 | 67897832 | 1920 | 2097152, true); if (success && success !== unknownSymbol) { return success; } @@ -45358,9 +46524,9 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 209) { - meaning = 67901928; + meaning = 67897832; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319; + meaning |= 67220415; } } else { @@ -45376,7 +46542,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 && entityName.parent.parent.kind === 301) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); + ts.Debug.assert(!ts.isInJSFile(entityName)); var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -45389,7 +46555,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319, false, true); + return resolveEntityName(entityName, 67220415, false, true); } else if (entityName.kind === 187 || entityName.kind === 146) { var links = getNodeLinks(entityName); @@ -45406,7 +46572,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 ? 67901928 : 1920; + var meaning = entityName.parent.kind === 162 ? 67897832 : 1920; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 265) { @@ -45476,7 +46642,7 @@ var ts; case 13: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 || node.parent.kind === 253) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -45490,6 +46656,7 @@ var ts; case 79: case 89: case 36: + case 75: return getSymbolOfNode(node.parent); case 181: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -45499,34 +46666,29 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274) { - return resolveEntityName(location.name, 67216319 | 2097152); + return resolveEntityName(location.name, 67220415 | 2097152); } return undefined; } function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 | 67901928 | 1920 | 2097152); + resolveEntityName(node.propertyName || node.name, 67220415 | 67897832 | 1920 | 2097152); } function getTypeOfNode(node) { if (node.flags & 8388608) { return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + if (classType && !classDecl.isImplements) { var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -45593,11 +46755,30 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71: + return getLiteralType(ts.idText(name)); + case 8: + case 9: + return getLiteralType(name.text); + case 147: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -45652,13 +46833,13 @@ var ts; var symbolLinks = getSymbolLinks(moduleSymbol); if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319) + ? !!(moduleSymbol.flags & 67220415) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319); + return s && !!(s.flags & 67220415); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -45693,7 +46874,7 @@ var ts; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); - if (isNonLocalAlias(symbol, 67216319)) { + if (isNonLocalAlias(symbol, 67220415)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -45706,11 +46887,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319, undefined, undefined, false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415, undefined, undefined, false)) { links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072) { - var isDeclaredInLoop = nodeLinks_1.flags & 262144; + else if (nodeLinks_1.flags & 262144) { + var isDeclaredInLoop = nodeLinks_1.flags & 524288; var inLoopInitializer = ts.isIterationStatement(container, false); var inLoopBodyBlock = container.kind === 216 && ts.isIterationStatement(container.parent, false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -45778,7 +46959,7 @@ var ts; if (target === unknownSymbol) { return true; } - return !!(target.flags & 67216319) && + return !!(target.flags & 67220415) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -45791,7 +46972,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; - if (target && ts.getModifierFlags(node) & 1 && target.flags & 67216319) { + if (target && ts.getModifierFlags(node) & 1 && target.flags & 67220415) { return true; } } @@ -45824,6 +47005,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -45865,8 +47065,8 @@ var ts; if (!location) return ts.TypeReferenceSerializationKind.Unknown; } - var valueSymbol = resolveEntityName(typeName, 67216319, true, false, location); - var typeSymbol = resolveEntityName(typeName, 67901928, true, false, location); + var valueSymbol = resolveEntityName(typeName, 67220415, true, false, location); + var typeSymbol = resolveEntityName(typeName, 67897832, true, false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -45964,7 +47164,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 | 1048576 | 2097152, undefined, undefined, true); + return resolveName(location, reference.escapedText, 67220415 | 1048576 | 2097152, undefined, undefined, true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -45979,18 +47179,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 && type.flags & 33554432); + return !!(type.flags & 448 && type.flags & 33554432); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 ? nodeBuilder.symbolToExpression(type.symbol, 67220415, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); @@ -46028,6 +47230,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -46069,7 +47273,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 && node.parent.parent && node.parent.parent.kind === 271; @@ -46078,9 +47287,9 @@ var ts; if (!fileToDirective) { return undefined; } - var meaning = 67901928 | 1920; + var meaning = 67897832 | 1920; if ((node.kind === 71 && isInTypeQuery(node)) || (node.kind === 187 && !isInHeritageClause(node))) { - meaning = 67216319 | 1048576; + meaning = 67220415 | 1048576; } var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -46158,6 +47367,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -46191,6 +47403,8 @@ var ts; globalArrayType = getGlobalType("Array", 1, true); globalObjectType = getGlobalType("Object", 0, true); globalFunctionType = getGlobalType("Function", 0, true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", 0, true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", 0, true) || globalFunctionType; globalStringType = getGlobalType("String", 0, true); globalNumberType = getGlobalType("Number", 0, true); globalBooleanType = getGlobalType("Boolean", 0, true); @@ -46215,29 +47429,28 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -46249,7 +47462,7 @@ var ts; for (var helper = 1; helper <= 65536; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -46617,10 +47830,31 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -46794,6 +48028,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { @@ -46818,8 +48055,9 @@ var ts; } var currentKind = void 0; switch (prop.kind) { - case 273: case 274: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + case 273: checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8) { checkGrammarNumericLiteral(name); @@ -47022,6 +48260,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -47108,24 +48349,32 @@ var ts; expr.kind === 200 && expr.operator === 38 && expr.operand.kind === 8; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 || node.initializer.kind === 86); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 && node.parent.parent.kind !== 225) { if (node.flags & 4194304) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -47259,10 +48508,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -47293,8 +48543,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 || ts.hasModifier(node, 32 | 128))) { @@ -50550,6 +51800,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -50558,19 +51823,7 @@ var ts; } ts.startsWithUseStrict = startsWithUseStrict; function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -52706,8 +53959,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 - && !(element.transformFlags & (524288 | 1048576)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 | 1048576)) + && !(element.transformFlags & (131072 | 262144)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 | 262144)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -52754,7 +54007,7 @@ var ts; for (var i = 0; i < numElements; i++) { var element = elements[i]; if (flattenContext.level >= 1) { - if (element.transformFlags & 1048576) { + if (element.transformFlags & 262144) { var temp = ts.createTempVariable(undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -53304,7 +54557,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); @@ -53333,9 +54586,11 @@ var ts; return ts.setTextRange(ts.createNodeArray(members), node.members); } function transformConstructor(node, isDerivedClass) { - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { return ts.visitEachChild(constructor, visitor, context); } @@ -54420,7 +55675,7 @@ var ts; return ts.getGeneratedNameForNode(node); } function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608) { + if (resolver.getNodeCheckFlags(node) & 16777216) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -54521,7 +55776,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1) { - if (resolver.getNodeCheckFlags(node) & 16777216) { + if (resolver.getNodeCheckFlags(node) & 33554432) { var declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { var classAlias = classAliases[declaration.id]; @@ -54634,6 +55889,9 @@ var ts; var enabledSubstitutions; var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + var capturedSuperProperties; + var hasSuperElementAccess; + var substitutedSuperAccessors = []; var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; @@ -54664,6 +55922,16 @@ var ts; return visitFunctionExpression(node); case 195: return visitArrowFunction(node); + case 187: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188: + if (capturedSuperProperties && node.expression.kind === 97) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -54848,21 +56116,30 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); - if (languageVersion >= 2) { + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -54880,6 +56157,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -54912,6 +56191,7 @@ var ts; context.enableEmitNotification(156); context.enableEmitNotification(157); context.enableEmitNotification(155); + context.enableEmitNotification(217); } } function onEmitNode(hint, node, emitCallback) { @@ -54925,6 +56205,13 @@ var ts; return; } } + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } function onSubstituteNode(hint, node) { @@ -54947,13 +56234,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -54977,16 +56264,38 @@ var ts; || kind === 156 || kind === 157; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), undefined, [argumentExpression]), "value"), location); + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), undefined, [argumentExpression]), location); + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + function createSuperAccessVariableStatement(resolver, node, names) { + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "v", undefined, undefined, undefined) + ], undefined, undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, true) + ])) + ], 2)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -55007,12 +56316,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); var ts; @@ -55029,6 +56338,9 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + var capturedSuperProperties; + var hasSuperElementAccess; + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -55097,6 +56409,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272: return visitCatchClause(node); + case 187: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188: + if (capturedSuperProperties && node.expression.kind === 97) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -55160,7 +56482,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576) { + if (node.transformFlags & 262144) { var objects = chunkObjectLiteralElements(node.properties); if (objects.length && objects[0].kind !== 186) { objects.unshift(ts.createObjectLiteral()); @@ -55182,7 +56504,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144) { return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); } else if (node.operatorToken.kind === 26) { @@ -55191,7 +56513,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144) { return ts.flattenDestructuringBinding(node, visitor, context, 1); } return ts.visitEachChild(node, visitor, context); @@ -55203,7 +56525,7 @@ var ts; return ts.visitEachChild(node, visitorNoDestructuringValue, context); } function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576) { + if (node.initializer.transformFlags & 262144) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -55290,7 +56612,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576) { + if (node.transformFlags & 262144) { return ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); @@ -55367,19 +56689,31 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); + var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); - if (languageVersion >= 2) { + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -55403,7 +56737,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576) { + if (parameter.transformFlags & 262144) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); if (ts.some(declarations)) { @@ -55426,6 +56760,7 @@ var ts; context.enableEmitNotification(156); context.enableEmitNotification(157); context.enableEmitNotification(155); + context.enableEmitNotification(217); } } function onEmitNode(hint, node, emitCallback) { @@ -55439,6 +56774,13 @@ var ts; return; } } + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } function onSubstituteNode(hint, node) { @@ -55461,13 +56803,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -55491,12 +56833,12 @@ var ts; || kind === 156 || kind === 157; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value"), location); + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), location); + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), undefined, [argumentExpression]), location); } } } @@ -56127,7 +57469,7 @@ var ts; return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 216))) - || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432) !== 0; } function visitor(node) { @@ -56549,7 +57891,7 @@ var ts; } if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 | 32768))) { + && !(ctor.transformFlags & (8192 | 16384))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 || superCallExpression.left.kind !== 189) { @@ -56586,7 +57928,7 @@ var ts; } } function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072) !== 0; + return (node.transformFlags & 65536) !== 0; } function addDefaultValueAssignmentsIfNeeded(statements, node) { if (!shouldAddDefaultValueAssignments(node)) { @@ -56653,7 +57995,7 @@ var ts; statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 && node.kind !== 195) { + if (node.transformFlags & 16384 && node.kind !== 195) { captureThisForNode(statements, node, ts.createThis()); } } @@ -56785,7 +58127,7 @@ var ts; return call; } function visitArrowFunction(node) { - if (node.transformFlags & 16384) { + if (node.transformFlags & 8192) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -56993,21 +58335,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 + if (node.transformFlags & 2097152 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } function shouldEmitExplicitInitializerForLetDeclaration(node) { var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072; - var isDeclaredInLoop = flags & 262144; + var isCapturedInFunction = flags & 262144; + var isDeclaredInLoop = flags & 524288; var emittedAsTopLevel = (hierarchyFacts & 64) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -57188,7 +58536,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 && hierarchyFacts & 4) + if ((property.transformFlags & 4194304 && hierarchyFacts & 4) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -57214,7 +58562,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536) !== 0; } function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { @@ -57237,7 +58601,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; @@ -57251,7 +58615,68 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224: return convertForInStatement(node, convertedLoopBody); + case 225: return convertForOfStatement(node, convertedLoopBody); + case 221: return convertDoStatement(node, convertedLoopBody); + case 222: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223: @@ -57266,150 +58691,175 @@ var ts; var loopParameters = []; var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { - if (outerConvertedLoopState.argumentsName) { - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { + if (convertedLoopState.argumentsName) { + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { - convertedLoopState.thisName = outerConvertedLoopState.thisName; + if (convertedLoopState.thisName) { + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + if (convertedLoopState.hoistedLocalVariables) { + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], true); - } - var containsYield = (node.statement.transformFlags & 16777216) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144; - } - var convertedLoopVariable = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) - ]), 2097152)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; - if (currentState.argumentsName) { - if (outerConvertedLoopState) { - outerConvertedLoopState.argumentsName = currentState.argumentsName; + if (state.argumentsName) { + if (outerState) { + outerState.argumentsName = state.argumentsName; } else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, undefined, ts.createIdentifier("arguments"))); + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { - if (outerConvertedLoopState) { - outerConvertedLoopState.thisName = currentState.thisName; + if (state.thisName) { + if (outerState) { + outerState.thisName = state.thisName; } else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, undefined, ts.createIdentifier("this"))); + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { - if (outerConvertedLoopState) { - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + if (state.hoistedLocalVariables) { + if (outerState) { + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, undefined, ts.createFalse())); + } if (extraVariableDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, undefined, p.outParamName); + } + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8; + if (containsYield && hierarchyFacts & 4) + emitFlags |= 262144; + var statements = []; + statements.push(ts.createVariableStatement(undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2, 1, statements); + var functionDeclaration = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, undefined, undefined, ts.visitNode(ts.createBlock(statements, true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - clone_3.statement = undefined; - clone_3 = ts.visitEachChild(clone_3, visitor, context); - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, true); - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1, 1, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8; + if (containsYield && (hierarchyFacts & 4) !== 0) + emitFlags |= 262144; + var functionDeclaration = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, currentState.loopParameters, undefined, loopBody), emitFlags)) + ]), 2097152)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 8388608)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; var isSimpleLoop = !(state.nonLocalJumps & ~4) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 8388608)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0, statements); + copyOutParameters(state.loopOutParameters, 1, 0, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0, statements); + copyOutParameters(state.loopOutParameters, 1, 0, statements); if (state.nonLocalJumps & 8) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8; + if (outerState) { + outerState.nonLocalJumps |= 8; returnStatement = ts.createReturn(loopResultName); } else { @@ -57422,8 +58872,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -57460,21 +58910,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304) { + flags |= 1; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -57569,7 +59027,7 @@ var ts; var ancestorFacts = enterSubtree(16286, 65); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 | 128) + var body = node.transformFlags & (16384 | 128) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156) { @@ -57650,7 +59108,7 @@ var ts; return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { - if (node.transformFlags & 524288 || + if (node.transformFlags & 131072 || node.expression.kind === 97 || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -57658,7 +59116,7 @@ var ts; ts.setEmitFlags(thisArg, 4); } var resultingCall = void 0; - if (node.transformFlags & 524288) { + if (node.transformFlags & 131072) { resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { @@ -57677,7 +59135,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitNewExpression(node) { - if (node.transformFlags & 524288) { + if (node.transformFlags & 131072) { var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); } @@ -57981,7 +59439,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -58167,10 +59625,10 @@ var ts; case 228: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216) { + if (node.transformFlags & 4194304) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 | 33554432)) { + else if (node.transformFlags & (512 | 8388608)) { return ts.visitEachChild(node, visitor, context); } else { @@ -58306,7 +59764,7 @@ var ts; return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); } function visitVariableStatement(node) { - if (node.transformFlags & 16777216) { + if (node.transformFlags & 4194304) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -58389,10 +59847,10 @@ var ts; else if (node.operatorToken.kind === 26) { return visitCommaExpression(node); } - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -58519,10 +59977,10 @@ var ts; } function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -58987,7 +60445,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216) !== 0; + return !!node && (node.transformFlags & 4194304) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -59019,10 +60477,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -59726,7 +61184,10 @@ var ts; var needUMDDynamicImportHelper; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -59767,17 +61228,20 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; var _a = collectAsynchronousDependencies(node, true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createExpressionStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), - ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ - ts.createParameter(undefined, undefined, undefined, "require"), - ts.createParameter(undefined, undefined, undefined, "exports") - ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "require"), + ts.createParameter(undefined, undefined, undefined, "exports") + ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ]))) ]), node.statements)); ts.addEmitHelpers(updated, context.readEmitHelpers()); @@ -59925,7 +61389,7 @@ var ts; } } function moduleExpressionElementVisitor(node) { - if (!(node.transformFlags & 67108864) && !(node.transformFlags & 2048)) { + if (!(node.transformFlags & 16777216) && !(node.transformFlags & 2048)) { return node; } if (ts.isImportCall(node)) { @@ -59992,7 +61456,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384); + var containsLexicalThis = !!(node.transformFlags & 8192); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -60603,7 +62067,7 @@ var ts; var noSubstitution; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216)) { return node; } var id = ts.getOriginalNodeId(node); @@ -61224,7 +62688,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048) || (node.transformFlags & 67108864)) { + else if ((node.transformFlags & 2048) || (node.transformFlags & 16777216)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -61867,7 +63331,7 @@ var ts; function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 238) { - diagnosticMessage = node.parent.token === 108 ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -61900,11 +63364,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -61924,7 +63388,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -61942,6 +63406,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -61951,10 +63416,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -62018,15 +63483,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -62038,11 +63504,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], true, [], [], false, []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], true, [], [], false, []); return newFile; } needsDeclare = true; @@ -62055,6 +63522,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -62072,8 +63540,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -62084,11 +63553,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([]), undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { if (emittedImports) { @@ -62117,20 +63589,23 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; var paths = ts.getOutputPathsFor(file, host, true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -62140,6 +63615,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71) { return name; @@ -62598,7 +64082,22 @@ var ts; return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 237: { - return cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + var clean = cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, undefined); + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242: { needsDeclare = false; @@ -62807,7 +64306,7 @@ var ts; var prop = ts.createProperty(undefined, maskModifiers(node, undefined, (!accessors.setAccessor) ? 64 : 0), node.name, node.questionToken, ensureType(node, accessorType), undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -62821,7 +64320,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -62865,10 +64364,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235: case 152: case 151: + return !ts.hasModifier(node, 8); case 149: + case 235: return true; } return false; @@ -63675,7 +65175,7 @@ var ts; emitCallback(node); } if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + ts.performance.mark("beginEmitBodyWithDetachedComments"); } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, true); @@ -63684,7 +65184,7 @@ var ts; } } if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedComments"); } } function emitLeadingComments(pos, isEmittedNode) { @@ -63875,19 +65375,23 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); - var isJs = ts.isSourceFileJavaScript(sourceFile); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -63906,7 +65410,7 @@ var ts; return ".json"; } if (options.jsx === 1) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { return ".jsx"; } @@ -63951,25 +65455,30 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, false); @@ -63987,11 +65496,11 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { nonJsFiles.forEach(collectLinkedAliases); @@ -64670,7 +66179,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -64682,7 +66191,7 @@ var ts; emitLiteral(node); } function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -65080,7 +66589,7 @@ var ts; function needsDotDotForPropertyAccess(expression) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23)); } @@ -65271,7 +66780,7 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -65935,13 +67444,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -65967,11 +67476,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -66126,7 +67640,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos - && !(ts.isArrowFunction(parentNode) && parentNode.type) + && ts.isArrowFunction(parentNode) + && !parentNode.type && !ts.some(parentNode.decorators) && !ts.some(parentNode.modifiers) && !ts.some(parentNode.typeParameters) @@ -66516,19 +68031,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } function pushNameGenerationScope(node) { if (node && ts.getEmitFlags(node) & 524288) { @@ -66683,7 +68198,7 @@ var ts; for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); - if (local && local.flags & (67216319 | 1048576 | 2097152)) { + if (local && local.flags & (67220415 | 1048576 | 2097152)) { return false; } } @@ -66748,7 +68263,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, true); } function generateNameForModuleOrEnum(node) { @@ -67189,15 +68704,20 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -67213,7 +68733,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -67223,7 +68743,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -67231,8 +68751,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); - var mtimeBefore = ts.sys.getModifiedTime(fileName); + var hash = system.createHash(data); + var mtimeBefore = system.getModifiedTime(fileName); if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); if (fingerprint && @@ -67242,8 +68762,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -67254,11 +68774,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -67270,36 +68790,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -67307,8 +68824,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -67333,7 +68850,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -67412,8 +68929,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); @@ -67428,11 +68945,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -67486,13 +69003,16 @@ var ts; } return resolutions; } - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; } if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; } @@ -67508,8 +69028,21 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -67519,16 +69052,12 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; function shouldProgramCreateNewSourceFiles(program, newOptions) { - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -67569,7 +69098,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json"]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; var _referencesArrayLiteralSyntax; @@ -67606,7 +69135,7 @@ var ts; var missingFilePaths; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { @@ -67618,11 +69147,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, false, false, undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -67698,7 +69228,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -67731,7 +69263,7 @@ var ts; if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } @@ -67761,13 +69293,13 @@ var ts; } var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } var unknownModuleNames; var result; @@ -67825,19 +69357,15 @@ var ts; ts.Debug.assert(j === resolutions.length); return result; function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -67863,30 +69391,30 @@ var ts; if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { return oldProgram.structureIsReused = 0; } - var oldRefs = oldProgram.getProjectReferences(); + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0; + } + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0; - } + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { return oldProgram.structureIsReused = 0; } } else { - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0; - } + ts.Debug.assert(!oldRefs); } var newSourceFiles = []; var filePaths = []; @@ -67900,7 +69428,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, undefined, shouldCreateNewSourceFile); if (!newSourceFile) { return oldProgram.structureIsReused = 0; @@ -67924,6 +69452,9 @@ var ts; fileChanged = newSourceFile !== oldSourceFile; } newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -67971,7 +69502,7 @@ var ts; modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -67986,7 +69517,7 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -68018,14 +69549,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { var path = toPath(f); if (getSourceFileByPath(path)) return true; @@ -68034,11 +69572,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -68048,11 +69587,12 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { - if (!resolvedRefOpts.options.outFile) + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -68104,7 +69644,7 @@ var ts; } if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -68158,9 +69698,9 @@ var ts; } } function getSyntacticDiagnosticsForFile(sourceFile) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -68234,7 +69774,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -68447,7 +69987,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); var imports; var moduleAugmentations; @@ -68535,7 +70075,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -68589,11 +70129,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -68607,6 +70150,7 @@ var ts; return redirect; } function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames) { @@ -68659,7 +70203,7 @@ var ts; var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -68679,6 +70223,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); var existingFile = filesByNameIgnoreCase.get(pathLowerCase); @@ -68706,22 +70251,22 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts") || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts") : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, false, undefined, file, ref.pos, ref.end); }); } @@ -68730,7 +70275,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -68806,7 +70351,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -68815,7 +70360,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -68828,7 +70373,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -68847,34 +70392,26 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } return allFilesBelongToPath; } function parseProjectReferenceConfigFile(ref) { - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100); if (sourceFile === undefined) { @@ -68884,22 +70421,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -68939,9 +70470,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -68950,17 +70482,16 @@ var ts; } } } - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -69009,15 +70540,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -69042,7 +70573,7 @@ var ts; var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -69055,8 +70586,8 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } if (options.outDir || @@ -69067,15 +70598,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -69256,7 +70787,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts")) || !!getSourceFileByPath((filePathWithoutExtension + ".tsx")); @@ -69271,7 +70802,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -69279,13 +70813,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { @@ -69342,13 +70877,16 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } function getReferencedFileFromImportLiteral(checker, importName) { var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } function getReferencedFiles(program, sourceFile, getCanonicalFileName) { var referencedFiles; if (sourceFile.imports && sourceFile.imports.length > 0) { @@ -69365,7 +70903,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -69375,11 +70913,41 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + addReferenceFromAmbientModule(symbol); + } + } + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -69769,7 +71337,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -69782,7 +71350,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -69908,16 +71483,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { getProgram: function () { return program; }, getState: ts.notImplemented, @@ -70046,7 +71621,7 @@ var ts; return primaryResult; } var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (resolvedModule) { return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; @@ -70166,7 +71741,7 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -70458,87 +72033,100 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 : importModuleSpecifierPreference === "non-relative" ? 1 : 2, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0; + case "index": return 1; + case "js": return 2; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 : 0; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 : 1, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 : 0, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2) + ts.Debug.assertNever(relativePreference); + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47) + count++; } - 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]; + return count; } 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; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -70596,16 +72184,6 @@ var ts; result.push.apply(result, targets); return result; } - 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 = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -70623,7 +72201,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -70643,39 +72222,43 @@ var ts; 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) { + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; 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 (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -70687,6 +72270,8 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; @@ -70744,13 +72329,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json")) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0: + return ts.removeSuffix(noExtension, "/index"); + case 1: + return noExtension; + case 2: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts": + case ".d.ts": + return ".js"; + case ".tsx": + return options.jsx === 1 ? ".jsx" : ".js"; + case ".js": + case ".jsx": + case ".json": + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); @@ -70785,16 +72393,12 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { if (system.clearScreen && !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -70836,7 +72440,7 @@ var ts; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); @@ -70848,7 +72452,7 @@ var ts; reportSemanticDiagnostics = true; } } - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -70879,6 +72483,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + 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 args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { if (system === void 0) { system = ts.sys; } if (!createProgram) { @@ -70888,7 +72511,7 @@ var ts; host; var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -70902,17 +72525,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - 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 args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -70952,18 +72568,19 @@ var ts; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -70986,9 +72603,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -71056,7 +72674,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -71089,9 +72708,9 @@ var ts; } } var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(undefined, undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(undefined, undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -71115,7 +72734,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); if (needsUpdateInTypeRootWatch) { @@ -71275,12 +72894,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -71304,7 +72918,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -71395,7 +73011,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -71407,87 +73024,61 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - function createFileMap() { + function createFileMap(toPath) { var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts"); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json") ? ".json" : @@ -71499,7 +73090,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json")) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -71510,13 +73105,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts"); + var dts = ts.changeExtension(out, ".d.ts"); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -71527,748 +73126,746 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts"); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); + }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + var unchangedOutputs = createFileMap(toPath); + var projectStatus = createFileMap(toPath); var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects - }; - } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - addProject(arg); - } - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } - } - ts.performBuild = performBuild; - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1)); - }); - } - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + watchWildCardDirectories(resolved, cfg); + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + if (!ts.fileExtensionIs(fileName, ".d.ts") && + (ts.fileExtensionIs(fileName, ".ts") || ts.fileExtensionIs(fileName, ".tsx"))) { + return false; + } + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts"))) { + return true; + } + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + function getFilesToClean() { + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); if (defaultOptions.dry) { - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } - function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } + function reportBuildQueue(graph) { + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json")) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -72303,6 +73900,7 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: + case UpToDateStatusType.ComputingUpstream: break; default: ts.assertType(status); @@ -72310,6 +73908,131 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +var ts; +(function (ts) { + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; + } + function anyValue(name, comment) { + return { kind: 0, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.release.js.map var ts; (function (ts) { @@ -72330,7 +74053,7 @@ var ts; return !!ts.sys.writeOutputIsTTY && ts.sys.writeOutputIsTTY(); } function shouldBePretty(options) { - if (typeof options.pretty === "undefined") { + if (!options || typeof options.pretty === "undefined") { return defaultIsPretty(); } return options.pretty; @@ -72354,28 +74077,10 @@ var ts; ts.filter(ts.optionDeclarations.slice(), function (v) { return !!v.showInSimplifiedHelpView; }); } function executeCommandLine(args) { - if (args.length > 0 && ((args[0].toLowerCase() === "--build") || (args[0].toLowerCase() === "-b"))) { - var reportDiag_1 = ts.createDiagnosticReporter(ts.sys, defaultIsPretty()); - var report = function (message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return reportDiag_1(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); - }; - var buildHost = { - error: report, - verbose: report, - message: report, - errorDiagnostic: function (d) { return reportDiag_1(d); } - }; - var result = ts.performBuild(args.slice(1), ts.createCompilerHost({}), buildHost, ts.sys); - // undefined = in watch mode, do not exit - if (result !== undefined) { - return ts.sys.exit(result); - } - else { - return; + if (args.length > 0 && args[0].charCodeAt(0) === 45 /* minus */) { + var firstOption = args[0].slice(args[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); + if (firstOption === "build" || firstOption === "b") { + return performBuild(args.slice(1)); } } var commandLine = ts.parseCommandLine(args); @@ -72467,6 +74172,42 @@ var ts; ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } + function performBuild(args) { + var _a = ts.parseBuildCommand(args), buildOptions = _a.buildOptions, projects = _a.projects, errors = _a.errors; + if (errors.length > 0) { + errors.forEach(reportDiagnostic); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (buildOptions.help) { + ts.printVersion(); + ts.printHelp(ts.buildOpts, "--build "); + return ts.sys.exit(ts.ExitStatus.Success); + } + // Update to pretty if host supports it + updateReportDiagnostic(); + if (projects.length === 0) { + ts.printVersion(); + ts.printHelp(ts.buildOpts, "--build "); + return ts.sys.exit(ts.ExitStatus.Success); + } + if (!ts.sys.getModifiedTime || !ts.sys.setModifiedTime || (buildOptions.clean && !ts.sys.deleteFile)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (buildOptions.watch) { + reportWatchModeWithoutSysSupport(); + } + // TODO: change this to host if watch => watchHost otherwiue without wathc + var builder = ts.createSolutionBuilder(ts.createSolutionBuilderWithWatchHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createWatchStatusReporter()), projects, buildOptions); + if (buildOptions.clean) { + return ts.sys.exit(builder.cleanAllProjects()); + } + if (buildOptions.watch) { + builder.buildAllProjects(); + return builder.startWatching(); + } + return ts.sys.exit(builder.buildAllProjects()); + } function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) { var host = ts.createCompilerHost(options); enableStatistics(options); @@ -72484,12 +74225,12 @@ var ts; } function updateWatchCompilationHost(watchCompilerHost) { var compileUsingBuilder = watchCompilerHost.createProgram; - watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) { ts.Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); if (options !== undefined) { enableStatistics(options); } - return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics); + return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); }; var emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; // TODO: GH#18217 watchCompilerHost.afterProgramCreate = function (builderProgram) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 4111b40028b..ac46ae0c134 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -86,7 +86,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -101,6 +101,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -729,17 +730,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -784,7 +791,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1161,7 +1168,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1281,6 +1288,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1445,7 +1456,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1948,6 +1961,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2042,6 +2059,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2628,6 +3005,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2678,6 +3056,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2747,38 +3127,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2853,14 +3233,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -3006,9 +3387,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3027,22 +3407,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3279,25 +3659,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3316,25 +3692,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3578,20 +3953,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3809,17 +4170,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4140,11 +4505,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4755,7 +5121,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4794,6 +5160,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5037,7 +5407,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5065,6 +5434,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5156,6 +5533,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5269,7 +5647,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5363,7 +5743,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5461,6 +5841,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5491,9 +5880,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5558,6 +5947,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5686,10 +6076,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { return token >= 71 /* Identifier */; @@ -5700,136 +6093,85 @@ var ts; return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 117 /* AbstractKeyword */, + any: 119 /* AnyKeyword */, + as: 118 /* AsKeyword */, + boolean: 122 /* BooleanKeyword */, + break: 72 /* BreakKeyword */, + case: 73 /* CaseKeyword */, + catch: 74 /* CatchKeyword */, + class: 75 /* ClassKeyword */, + continue: 77 /* ContinueKeyword */, + const: 76 /* ConstKeyword */ + }, + _a["" + "constructor"] = 123 /* ConstructorKeyword */, + _a.debugger = 78 /* DebuggerKeyword */, + _a.declare = 124 /* DeclareKeyword */, + _a.default = 79 /* DefaultKeyword */, + _a.delete = 80 /* DeleteKeyword */, + _a.do = 81 /* DoKeyword */, + _a.else = 82 /* ElseKeyword */, + _a.enum = 83 /* EnumKeyword */, + _a.export = 84 /* ExportKeyword */, + _a.extends = 85 /* ExtendsKeyword */, + _a.false = 86 /* FalseKeyword */, + _a.finally = 87 /* FinallyKeyword */, + _a.for = 88 /* ForKeyword */, + _a.from = 143 /* FromKeyword */, + _a.function = 89 /* FunctionKeyword */, + _a.get = 125 /* GetKeyword */, + _a.if = 90 /* IfKeyword */, + _a.implements = 108 /* ImplementsKeyword */, + _a.import = 91 /* ImportKeyword */, + _a.in = 92 /* InKeyword */, + _a.infer = 126 /* InferKeyword */, + _a.instanceof = 93 /* InstanceOfKeyword */, + _a.interface = 109 /* InterfaceKeyword */, + _a.is = 127 /* IsKeyword */, + _a.keyof = 128 /* KeyOfKeyword */, + _a.let = 110 /* LetKeyword */, + _a.module = 129 /* ModuleKeyword */, + _a.namespace = 130 /* NamespaceKeyword */, + _a.never = 131 /* NeverKeyword */, + _a.new = 94 /* NewKeyword */, + _a.null = 95 /* NullKeyword */, + _a.number = 134 /* NumberKeyword */, + _a.object = 135 /* ObjectKeyword */, + _a.package = 111 /* PackageKeyword */, + _a.private = 112 /* PrivateKeyword */, + _a.protected = 113 /* ProtectedKeyword */, + _a.public = 114 /* PublicKeyword */, + _a.readonly = 132 /* ReadonlyKeyword */, + _a.require = 133 /* RequireKeyword */, + _a.global = 144 /* GlobalKeyword */, + _a.return = 96 /* ReturnKeyword */, + _a.set = 136 /* SetKeyword */, + _a.static = 115 /* StaticKeyword */, + _a.string = 137 /* StringKeyword */, + _a.super = 97 /* SuperKeyword */, + _a.switch = 98 /* SwitchKeyword */, + _a.symbol = 138 /* SymbolKeyword */, + _a.this = 99 /* ThisKeyword */, + _a.throw = 100 /* ThrowKeyword */, + _a.true = 101 /* TrueKeyword */, + _a.try = 102 /* TryKeyword */, + _a.type = 139 /* TypeKeyword */, + _a.typeof = 103 /* TypeOfKeyword */, + _a.undefined = 140 /* UndefinedKeyword */, + _a.unique = 141 /* UniqueKeyword */, + _a.unknown = 142 /* UnknownKeyword */, + _a.var = 104 /* VarKeyword */, + _a.void = 105 /* VoidKeyword */, + _a.while = 106 /* WhileKeyword */, + _a.with = 107 /* WithKeyword */, + _a.yield = 116 /* YieldKeyword */, + _a.async = 120 /* AsyncKeyword */, + _a.await = 121 /* AwaitKeyword */, + _a.of = 145 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, ">": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -6407,6 +6749,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6436,6 +6779,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6833,9 +7177,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -6891,6 +7235,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6929,6 +7274,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6986,6 +7349,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7491,7 +7859,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7568,6 +7936,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7588,7 +7959,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7670,22 +8040,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7790,6 +8147,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8014,12 +8377,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8046,13 +8417,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8421,6 +8792,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8481,6 +8856,7 @@ var ts; case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: case 138 /* SymbolKeyword */: + case 135 /* ObjectKeyword */: case 140 /* UndefinedKeyword */: case 131 /* NeverKeyword */: return true; @@ -9148,18 +9524,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9199,14 +9575,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9229,15 +9605,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9245,26 +9625,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9273,7 +9653,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9287,30 +9667,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9321,7 +9701,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9365,12 +9745,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9380,9 +9760,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9411,7 +9791,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9420,11 +9800,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9530,7 +9910,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9572,6 +9952,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9762,6 +10146,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9786,32 +10176,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9870,7 +10264,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9879,7 +10273,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10613,7 +11007,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10627,7 +11021,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10748,7 +11142,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10764,7 +11158,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11048,13 +11442,18 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -11076,15 +11475,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } @@ -11120,10 +11510,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11262,6 +11652,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11352,6 +11764,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11527,6 +11941,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11538,12 +11954,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11769,13 +12207,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12103,13 +12534,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12121,9 +12552,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12131,10 +12560,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12165,7 +12592,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12211,15 +12638,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12240,6 +12666,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12366,7 +12809,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13712,7 +14168,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14105,6 +14561,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14121,9 +14589,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14135,13 +14602,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14414,8 +14882,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14637,6 +15103,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14697,6 +15170,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14923,36 +15397,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15080,14 +15575,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15258,6 +15753,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -15346,6 +15857,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15416,6 +15928,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15774,7 +16287,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15943,8 +16456,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -16612,7 +17129,15 @@ var ts; // which would be a candidate for improved error reporting. return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 21 /* OpenBracketToken */: + case 39 /* AsteriskToken */: + case 24 /* DotDotDotToken */: + case 23 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: @@ -17380,8 +17905,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19477,8 +20004,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -20879,7 +21407,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -21004,13 +21532,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21025,7 +21546,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21096,7 +21619,7 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -21277,10 +21800,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21294,14 +21815,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21389,7 +21910,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21404,7 +21925,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21465,7 +21986,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21505,17 +22026,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21543,7 +22064,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21569,9 +22090,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -22412,8 +22931,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22427,6 +22945,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22474,21 +23028,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22503,6 +23042,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22521,6 +23062,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22533,6 +23075,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22540,6 +23083,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22557,6 +23101,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22666,6 +23211,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22674,6 +23220,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22682,14 +23229,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22698,6 +23255,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22706,6 +23264,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22739,6 +23298,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22751,6 +23311,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22758,6 +23319,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22767,6 +23329,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22782,6 +23345,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22793,6 +23357,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22803,6 +23368,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22887,30 +23453,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22969,12 +23517,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22987,6 +23537,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23032,6 +23583,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23039,6 +23591,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23066,6 +23619,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23093,7 +23647,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23146,20 +23738,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23195,16 +23788,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23216,7 +23808,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23224,7 +23816,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23260,7 +23852,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23303,9 +23895,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23318,7 +23920,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23632,7 +24262,11 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -23939,7 +24573,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23956,8 +24591,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23993,19 +24642,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24013,7 +24661,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24027,17 +24674,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24123,11 +24786,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24174,7 +24832,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24182,7 +24840,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24396,7 +25054,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24421,10 +25079,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24434,9 +25097,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24444,7 +25123,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24455,16 +25134,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24653,6 +25332,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24669,7 +25354,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24678,48 +25363,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24763,7 +25494,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24783,7 +25515,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24810,11 +25541,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24830,7 +25561,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24869,14 +25607,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -25099,15 +25841,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25145,7 +25887,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25164,7 +25906,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25175,74 +25917,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25254,8 +25982,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25263,7 +25991,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25277,7 +26005,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25294,29 +26022,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25324,7 +26053,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25365,52 +26094,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25424,12 +26147,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25443,40 +26166,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25488,6 +26204,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25499,51 +26216,56 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25563,87 +26285,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25651,11 +26415,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25664,43 +26428,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25708,24 +26473,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25740,9 +26505,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25957,13 +26722,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -26008,7 +26777,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26088,7 +26857,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26166,12 +26936,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26334,6 +27104,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -26432,6 +27203,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -26834,7 +27607,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -27230,7 +28002,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27250,7 +28022,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27338,9 +28110,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27360,7 +28129,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27585,7 +28354,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27632,7 +28401,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27649,15 +28418,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27730,15 +28499,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27754,7 +28523,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27765,9 +28534,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27848,37 +28617,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27914,7 +28681,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27944,7 +28711,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -28001,7 +28768,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28022,7 +28789,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28048,40 +28815,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28090,7 +28856,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28103,7 +28869,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28187,8 +28953,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28200,10 +28969,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28220,7 +28989,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28238,10 +29007,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28279,10 +29048,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28291,14 +29060,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28317,9 +29086,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28357,7 +29124,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(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; })); } @@ -28395,6 +29162,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28470,40 +29240,40 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28524,7 +29294,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28535,25 +29305,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28588,35 +29358,35 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28634,7 +29404,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28645,7 +29415,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28657,7 +29427,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28667,11 +29437,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28687,7 +29457,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28698,7 +29468,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28712,11 +29482,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28724,10 +29494,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28739,7 +29509,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28752,13 +29522,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28771,7 +29541,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28787,13 +29557,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28803,7 +29573,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28820,26 +29590,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28847,18 +29619,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28866,7 +29640,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28877,22 +29651,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28901,7 +29675,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28912,7 +29686,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28921,24 +29695,24 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 199 /* AwaitExpression */: @@ -29012,7 +29786,7 @@ var ts; case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: @@ -29059,8 +29833,8 @@ var ts; // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29069,58 +29843,58 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; case 150 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; @@ -29128,8 +29902,8 @@ var ts; break; case 185 /* ArrayLiteralExpression */: case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; @@ -29140,22 +29914,22 @@ var ts; case 223 /* ForStatement */: case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29177,27 +29951,27 @@ var ts; case 189 /* CallExpression */: case 190 /* NewExpression */: case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; + return 647001409 /* ModuleExcludes */; case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; + return 637535553 /* ParameterExcludes */; case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; + return 653604161 /* ArrowFunctionExcludes */; case 194 /* FunctionExpression */: case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; + return 653620545 /* FunctionExcludes */; case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; + return 639894849 /* VariableDeclarationListExcludes */; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; + return 638121281 /* ClassExcludes */; case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; + return 653616449 /* ConstructorExcludes */; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; + return 653616449 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: @@ -29216,12 +29990,12 @@ var ts; case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; + return 638358849 /* ObjectLiteralExcludes */; case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; + return 637797697 /* CatchClauseExcludes */; case 182 /* ObjectBindingPattern */: case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; + return 637666625 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: case 306 /* PartiallyEmittedExpression */: @@ -29230,9 +30004,9 @@ var ts; return 536872257 /* OuterExpressionExcludes */; case 187 /* PropertyAccessExpression */: case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29447,6 +30221,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29467,7 +30253,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29476,6 +30263,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -29683,8 +30471,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29752,7 +30540,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29782,8 +30571,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29817,6 +30619,7 @@ var ts; var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29828,6 +30631,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29846,6 +30651,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29857,7 +30663,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29946,6 +30751,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29988,6 +30795,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30123,35 +30932,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30184,7 +30993,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30197,8 +31006,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30219,53 +31029,54 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30373,8 +31184,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30517,7 +31328,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30526,15 +31337,23 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 149 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173 /* ConditionalType */) { @@ -30612,7 +31431,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30622,7 +31441,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30649,7 +31471,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30669,7 +31491,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30743,7 +31565,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30752,7 +31574,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30807,14 +31629,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30910,9 +31732,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30931,29 +31753,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30964,7 +31789,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30981,6 +31806,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31050,7 +31878,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31104,7 +31932,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31160,7 +31988,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31194,7 +32022,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31213,7 +32041,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31228,10 +32056,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31262,7 +32090,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31311,11 +32139,11 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31324,11 +32152,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31344,7 +32172,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31379,15 +32207,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31395,9 +32223,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31405,6 +32245,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31434,7 +32281,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31453,7 +32300,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31485,7 +32332,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31493,7 +32340,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31505,24 +32352,23 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -31750,7 +32596,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31850,7 +32696,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31900,7 +32746,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31965,11 +32814,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -32007,7 +32856,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32115,7 +32974,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32125,7 +32984,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32148,6 +33007,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32230,7 +33092,12 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -32275,13 +33142,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32301,7 +33168,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32368,17 +33235,20 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); @@ -32448,23 +33318,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32546,8 +33416,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32586,7 +33456,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32599,7 +33469,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32697,18 +33567,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32836,7 +33701,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32847,7 +33712,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32888,6 +33753,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32897,12 +33765,22 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -33009,7 +33887,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33017,7 +33902,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33116,6 +34001,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33174,7 +34062,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33358,10 +34246,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33382,7 +34270,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33431,6 +34319,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33439,6 +34329,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33603,27 +34495,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33631,11 +34523,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33683,7 +34575,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33714,16 +34606,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33743,16 +34641,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33766,8 +34664,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33775,9 +34673,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33785,7 +34683,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33796,15 +34694,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33823,7 +34719,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33837,10 +34733,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33864,9 +34760,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33889,8 +34783,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33898,7 +34792,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33912,8 +34806,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -34005,9 +34899,9 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -34050,19 +34944,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34076,7 +34977,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34137,7 +35038,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34165,14 +35066,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34195,7 +35094,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34223,7 +35122,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34232,11 +35131,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34261,7 +35160,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34270,22 +35169,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34444,23 +35335,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34531,7 +35419,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -34542,8 +35432,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34642,7 +35532,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34781,9 +35671,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -35009,7 +35899,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35029,7 +35919,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35283,7 +36173,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35420,7 +36310,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35443,7 +36333,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35497,6 +36387,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35608,7 +36499,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35778,10 +36669,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35798,7 +36694,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35877,6 +36774,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35884,8 +36782,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35907,8 +36815,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35923,7 +36831,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35933,9 +36841,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35985,6 +36890,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35992,14 +36911,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36029,10 +36949,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36123,8 +37043,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -36205,7 +37129,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36305,7 +37229,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36318,7 +37242,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36355,7 +37279,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36386,7 +37310,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36473,7 +37397,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36514,6 +37438,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36550,7 +37475,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36569,8 +37494,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36611,7 +37540,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36805,10 +37734,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36838,7 +37767,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36893,14 +37822,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36908,7 +37851,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36917,16 +37860,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -37042,16 +37990,16 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37100,10 +38048,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37131,6 +38079,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37157,7 +38108,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37278,6 +38229,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37346,10 +38305,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37364,15 +38320,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37418,7 +38365,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37446,7 +38393,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37543,10 +38490,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37555,8 +38499,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37810,7 +38754,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37823,20 +38767,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { @@ -37882,7 +38829,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37900,7 +38847,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37908,20 +38858,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37935,37 +38871,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37986,7 +38909,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38013,17 +38937,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38201,7 +39136,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38231,7 +39166,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38245,7 +39180,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38387,8 +39322,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38398,7 +39333,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38604,7 +39539,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38705,7 +39640,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38715,7 +39650,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38774,8 +39709,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38785,30 +39730,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38832,6 +39781,12 @@ var ts; var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38871,49 +39826,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38987,7 +39958,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39035,8 +40006,9 @@ var ts; return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 131072 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39062,33 +40034,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39097,15 +40134,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39114,10 +40151,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39128,13 +40165,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39168,8 +40208,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39201,9 +40241,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39252,8 +40297,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39283,9 +40328,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39308,11 +40354,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39338,13 +40384,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39508,10 +40554,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39646,10 +40692,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39705,13 +40751,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39810,7 +40853,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39820,32 +40863,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39862,8 +40879,8 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39901,13 +40918,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39936,7 +40956,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39963,32 +40984,24 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -40153,6 +41166,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40181,20 +41225,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40212,7 +41261,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40285,6 +41333,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40318,36 +41386,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40370,10 +41428,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40504,33 +41562,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40562,8 +41593,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40755,6 +41786,52 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41043,8 +42120,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41096,9 +42173,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -41120,10 +42202,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41148,13 +42230,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41166,7 +42252,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41180,11 +42266,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41421,8 +42508,12 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { case 202 /* BinaryExpression */: @@ -41445,44 +42536,49 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41658,7 +42754,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41744,11 +42842,13 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -41797,6 +42897,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41832,7 +42935,22 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41928,33 +43046,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41964,12 +43087,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ || kind === 155 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -42000,8 +43131,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42024,7 +43155,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42042,7 +43173,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42055,10 +43186,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42069,16 +43199,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42095,7 +43228,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42124,11 +43257,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42251,14 +43413,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144 /* Union */) { + if (type.flags & (16 /* Boolean */ | 512 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 /* Unit */ && !(combined & 15794176 /* Instantiable */)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -42302,6 +43480,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42310,8 +43500,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42319,8 +43516,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42357,13 +43554,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42403,7 +43602,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42489,10 +43688,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42538,6 +43737,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42562,6 +43778,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 /* Union */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144 /* Union */) { var types = type.types; @@ -42580,8 +43799,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42661,8 +43880,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42742,8 +43961,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42846,11 +44065,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42859,6 +44078,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42882,7 +44109,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42918,15 +44146,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43185,12 +44419,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43201,11 +44445,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43224,6 +44465,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43236,7 +44553,7 @@ var ts; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43253,22 +44570,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43392,8 +44699,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43401,7 +44708,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { if (node.kind === 71 /* Identifier */) { @@ -43449,7 +44756,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43493,8 +44800,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); @@ -43508,8 +44815,8 @@ var ts; while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43522,7 +44829,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43600,6 +44907,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || @@ -43624,22 +44934,42 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (container.kind === 223 /* ForStatement */ && ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; @@ -43781,31 +45111,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43820,13 +45148,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -43911,16 +45266,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43932,19 +45289,20 @@ var ts; // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; @@ -44052,7 +45410,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44109,7 +45467,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44176,9 +45534,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44225,7 +45595,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44246,13 +45616,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44262,9 +45639,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44282,19 +45659,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44312,6 +45716,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44319,10 +45725,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44342,8 +45744,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44408,47 +45810,36 @@ var ts; case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 71 /* Identifier */: + case 140 /* UndefinedKeyword */: return true; case 187 /* PropertyAccessExpression */: case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 268 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44488,6 +45879,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); + case 199 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); case 189 /* CallExpression */: case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); @@ -44513,7 +45906,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44532,6 +45925,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44540,7 +45939,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44612,11 +46011,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44722,8 +46121,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44759,7 +46158,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44781,7 +46180,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44790,7 +46189,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44802,35 +46201,47 @@ var ts; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44920,9 +46331,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44940,7 +46351,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45150,12 +46561,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45172,7 +46585,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45180,7 +46593,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45189,7 +46602,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45204,14 +46617,16 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45228,7 +46643,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45261,7 +46676,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45309,7 +46724,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45319,7 +46734,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45386,7 +46801,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45410,7 +46825,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45632,7 +47047,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45748,7 +47163,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45869,10 +47284,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45917,7 +47332,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46072,6 +47487,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46185,7 +47606,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46290,7 +47711,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46356,7 +47777,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46364,7 +47785,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46485,16 +47906,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46512,7 +47930,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46523,11 +47941,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46558,7 +47976,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46567,7 +47985,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46625,58 +48043,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46684,12 +48084,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46698,23 +48095,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46769,36 +48166,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46812,19 +48200,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46832,283 +48221,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 150 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47117,6 +48310,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47125,7 +48319,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47136,16 +48333,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47178,36 +48384,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47277,14 +48467,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47304,60 +48497,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47377,7 +48590,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47388,7 +48601,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47427,17 +48640,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47490,11 +48713,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47506,16 +48729,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47588,11 +48818,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47662,10 +48894,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47689,8 +48922,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47729,8 +48962,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47758,7 +48991,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47837,34 +49070,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47877,14 +49114,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47937,7 +49171,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47948,7 +49182,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47958,8 +49192,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47985,7 +49219,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48044,7 +49278,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48169,14 +49403,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48185,17 +49416,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48219,15 +49440,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48235,6 +49447,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48320,6 +49543,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48437,10 +49670,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48490,7 +49774,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48560,6 +49844,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48569,8 +49854,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48611,7 +49898,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48816,8 +50102,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48977,7 +50263,7 @@ var ts; if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -49003,8 +50289,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49118,7 +50404,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49256,9 +50542,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49273,15 +50559,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49334,8 +50620,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49344,7 +50630,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49450,7 +50736,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49492,19 +50778,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49535,11 +50817,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49586,15 +50868,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49608,9 +50894,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49621,13 +50911,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49646,13 +50936,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49677,7 +50967,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49770,9 +51060,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49802,7 +51089,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50268,7 +51555,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50299,7 +51586,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50400,8 +51687,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50640,6 +51927,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50697,13 +51991,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50733,10 +52020,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50966,7 +52253,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50989,7 +52276,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51046,7 +52333,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51304,8 +52591,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51315,7 +52602,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51801,7 +53088,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51884,7 +53171,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51924,7 +53211,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51940,7 +53227,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52314,13 +53601,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52347,9 +53638,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52890,7 +54183,10 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -52901,7 +54197,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52944,7 +54240,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52963,7 +54259,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -53127,6 +54423,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53616,8 +54914,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53628,7 +54926,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53681,14 +54979,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53742,13 +55040,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53779,7 +55077,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53811,7 +55109,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53859,7 +55157,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54026,7 +55324,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54097,13 +55395,20 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: @@ -54157,9 +55462,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54170,7 +55474,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54273,7 +55576,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54358,12 +55661,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54388,7 +55691,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54414,7 +55717,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54426,7 +55729,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54452,10 +55755,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54471,7 +55774,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54485,7 +55788,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54502,7 +55805,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54581,7 +55884,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54597,6 +55900,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54606,7 +55910,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54614,30 +55918,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54732,13 +56031,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54799,13 +56117,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54854,7 +56172,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54867,11 +56185,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54887,7 +56205,7 @@ var ts; // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -54963,7 +56281,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54976,7 +56294,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55021,6 +56339,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55065,9 +56402,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55169,7 +56506,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55184,18 +56521,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55238,6 +56577,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55279,7 +56620,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55293,9 +56639,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55384,6 +56730,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55428,6 +56777,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55455,31 +56806,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55491,7 +56841,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55865,11 +57215,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56047,6 +57418,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56090,8 +57464,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56308,6 +57684,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56404,26 +57783,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56563,10 +57948,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56597,8 +57983,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60174,6 +61560,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60187,19 +61588,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -62824,8 +64213,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62891,7 +64280,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63831,7 +65220,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63879,9 +65268,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -65795,7 +67186,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65917,7 +67308,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -66057,6 +67448,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66090,6 +67489,16 @@ var ts; return visitFunctionExpression(node); case 195 /* ArrowFunction */: return visitArrowFunction(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66331,23 +67740,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66365,6 +67784,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66400,6 +67821,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -66422,6 +67845,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66450,13 +67881,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66481,18 +67912,62 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66520,12 +67995,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66548,6 +68023,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66616,6 +68097,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272 /* CatchClause */: return visitCatchClause(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66680,7 +68171,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -66712,7 +68203,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 26 /* CommaToken */) { @@ -66727,7 +68218,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66744,7 +68235,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66841,7 +68332,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66938,25 +68429,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66980,7 +68483,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -67009,6 +68512,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -67031,6 +68536,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67059,13 +68572,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67090,13 +68603,13 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67754,6 +69267,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67934,7 +69452,7 @@ var ts; return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -68532,7 +70050,7 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 /* BinaryExpression */ || superCallExpression.left.kind !== 189 /* CallExpression */) { @@ -68603,7 +70121,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68732,7 +70250,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68920,7 +70438,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69210,19 +70728,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69270,8 +70796,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69526,7 +71052,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -69557,7 +71083,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69583,7 +71125,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69599,7 +71141,69 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 225 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 221 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 222 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223 /* ForStatement */: @@ -69616,165 +71220,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.thisName; } else { // this is top level converted loop so we need to create an alias for 'this' here // NOTE: // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69782,24 +71497,24 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { @@ -69812,8 +71527,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69853,21 +71568,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -70007,7 +71730,7 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156 /* GetAccessor */) { @@ -70186,7 +71909,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || node.expression.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -70194,7 +71917,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70241,7 +71964,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70723,7 +72446,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -71148,10 +72871,10 @@ var ts; case 228 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71354,7 +73077,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71478,10 +73201,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71742,10 +73465,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -72412,7 +74135,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72444,10 +74167,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -73529,7 +75252,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73583,6 +75309,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73613,22 +75340,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73862,7 +75591,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73929,7 +75658,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74894,7 +76623,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75979,7 +77708,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76786,7 +78515,7 @@ var ts; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -76821,11 +78550,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76851,7 +78580,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76869,6 +78598,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76878,10 +78608,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76950,15 +78680,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76970,11 +78701,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -76987,6 +78719,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -77005,8 +78738,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77017,11 +78751,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77051,7 +78788,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77059,13 +78796,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77075,6 +78817,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77591,10 +79342,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77817,7 +79583,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77831,7 +79597,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -77878,10 +79644,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -78883,7 +80650,7 @@ var ts; emitCallback(node); } if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + ts.performance.mark("beginEmitBodyWithDetachedComments"); } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); @@ -78892,7 +80659,7 @@ var ts; } } if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedComments"); } } function emitLeadingComments(pos, isEmittedNode) { @@ -79113,20 +80880,25 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79149,7 +80921,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79198,26 +80970,31 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -79242,12 +81019,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79976,7 +81753,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79998,7 +81775,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80423,7 +82200,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80634,7 +82411,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81337,13 +83116,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81369,11 +83148,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81538,7 +83322,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81959,19 +83744,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82150,7 +83935,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82229,7 +84014,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82743,17 +84528,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82769,7 +84561,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82779,7 +84571,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82787,8 +84579,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82799,8 +84591,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82811,11 +84603,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82827,36 +84619,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82864,8 +84653,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82891,7 +84680,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82979,8 +84768,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82995,11 +84784,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83057,7 +84846,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83066,6 +84855,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83086,8 +84879,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83097,21 +84906,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83162,7 +84967,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -83209,7 +85014,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83221,11 +85026,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83312,7 +85118,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83346,9 +85154,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83391,13 +85199,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83482,8 +85290,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83491,15 +85302,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83529,15 +85333,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83545,16 +85354,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83577,7 +85385,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83604,7 +85412,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83670,7 +85482,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83686,7 +85498,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83721,14 +85534,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83739,11 +85559,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83753,12 +85574,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83815,7 +85637,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83881,9 +85703,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83972,7 +85794,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84201,7 +86023,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84309,7 +86131,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84365,11 +86187,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84384,6 +86209,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84449,7 +86275,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -84470,6 +86296,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84499,24 +86326,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84526,7 +86355,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84613,7 +86442,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84622,7 +86451,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84642,7 +86471,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84662,27 +86491,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84690,7 +86511,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84701,22 +86522,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84756,9 +86571,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84768,17 +86584,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84828,15 +86643,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84863,7 +86678,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84876,9 +86691,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84893,15 +86708,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85092,7 +86907,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85109,7 +86924,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85117,17 +86935,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85197,7 +87012,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85207,6 +87022,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85230,7 +87051,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85241,11 +87062,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85765,7 +87620,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85778,7 +87633,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85952,16 +87814,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86110,7 +87972,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86248,7 +88110,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86588,121 +88451,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - 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]; + return count; } 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; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86766,16 +88625,6 @@ var ts; result.push.apply(result, targets); return result; } - 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 = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86793,7 +88642,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86813,25 +88663,30 @@ var ts; 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 + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // 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); @@ -86840,20 +88695,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; 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)) { // TODO: GH#18217 - 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 (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86868,12 +88721,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86936,13 +88791,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86981,11 +88859,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86994,7 +88867,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87044,7 +88917,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87060,7 +88933,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87094,6 +88967,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + 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 args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87106,7 +88998,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87120,17 +89012,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - 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 args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87179,18 +89064,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87213,9 +89099,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87286,7 +89173,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87324,9 +89212,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87351,7 +89239,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87532,12 +89420,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87563,7 +89446,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87650,6 +89535,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87670,7 +89557,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87687,94 +89575,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87787,7 +89646,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87798,13 +89661,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87815,808 +89682,820 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88652,7 +90531,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88660,6 +90541,142 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.js.map "use strict"; var __assign = (this && this.__assign) || function () { @@ -88735,6 +90752,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -88950,8 +90991,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89008,7 +91050,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89130,6 +91172,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89260,7 +91309,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89624,7 +91673,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -89642,8 +91691,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_1 && findRightmostToken(candidate_1, sourceFile); } else { // candidate should be in this node @@ -89651,15 +91700,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -89881,7 +91928,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -89995,7 +92042,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90003,7 +92050,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90145,6 +92192,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); @@ -90514,7 +92568,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90522,11 +92576,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -91671,9 +93725,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_1 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_1(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -91687,27 +93774,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_1 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_1(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -91722,8 +93797,8 @@ var ts; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; _loop_2(moduleName); } } @@ -91833,7 +93908,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -91866,7 +93941,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -91890,6 +93965,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -91997,11 +94084,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92017,7 +94105,7 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) @@ -92102,7 +94190,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92110,22 +94198,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92137,14 +94226,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92209,6 +94298,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92294,11 +94386,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92306,16 +94399,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92328,11 +94426,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92346,7 +94444,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92373,6 +94471,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -92781,7 +94884,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -92803,6 +94909,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -92811,6 +94918,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -92948,7 +95056,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -92963,9 +95071,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93002,7 +95108,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93030,12 +95136,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93054,7 +95160,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93075,7 +95181,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93105,7 +95211,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93129,6 +95235,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93364,7 +95477,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93398,14 +95512,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 71 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93559,10 +95678,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93574,6 +95690,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93594,7 +95712,6 @@ var ts; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: case 75 /* ClassKeyword */: case 76 /* ConstKeyword */: case 124 /* DeclareKeyword */: @@ -93609,6 +95726,8 @@ var ts; case 104 /* VarKeyword */: case 116 /* YieldKeyword */: return true; + case 120 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -93782,17 +95901,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -93815,7 +95936,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -93887,7 +96008,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -93907,14 +96028,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94379,9 +96500,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94426,7 +96544,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94440,7 +96558,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94507,6 +96625,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -94943,7 +97064,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95088,8 +97209,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95136,10 +97274,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95152,28 +97290,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_1 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_1, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_1 = def.node; return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_2 = def.node; var name_2 = ts.tokenToString(node_2.kind); return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_3 = def.node; var symbol = checker.getSymbolAtLocation(node_3); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")]; return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_4 = def.node; return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95191,24 +97329,61 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: name + ": " }; + } + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95240,17 +97415,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95266,7 +97441,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95330,11 +97560,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95348,7 +97578,7 @@ var ts; break; case 242 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95356,7 +97586,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95394,7 +97624,7 @@ var ts; 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: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!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); @@ -95525,15 +97755,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -95636,19 +97866,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -95678,7 +97895,7 @@ var ts; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -95801,7 +98018,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -95828,7 +98045,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -95998,12 +98215,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96233,7 +98451,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96291,8 +98509,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96300,39 +98519,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96344,8 +98549,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96358,11 +98581,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96370,19 +98595,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96471,14 +98696,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96574,7 +98799,7 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); var _loop_3 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); @@ -96602,7 +98827,7 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; @@ -96632,16 +98857,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -96655,7 +98887,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -96697,7 +98929,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -96963,6 +99195,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97173,7 +99415,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97206,7 +99448,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97269,7 +99511,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97329,7 +99571,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97721,7 +99963,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98047,28 +100289,49 @@ var ts; return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { @@ -99425,9 +101688,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; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99436,28 +101699,42 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); @@ -99508,22 +101785,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99532,17 +101819,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99559,12 +101850,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99581,9 +101872,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -99869,7 +102160,7 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { var _loop_6 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. @@ -99879,7 +102170,7 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { var state_2 = _loop_6(n); if (typeof state_2 === "object") return state_2.value; @@ -99895,10 +102186,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -99909,11 +102203,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -99967,7 +102278,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100091,13 +102402,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100120,7 +102431,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_1 = decl.symbol; if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) { @@ -100164,13 +102475,13 @@ var ts; switch (statement.kind) { case 217 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); case 219 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100195,10 +102506,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100208,7 +102519,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100227,22 +102538,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100375,13 +102709,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100519,7 +102856,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -100749,7 +103086,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -100821,7 +103158,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -100888,6 +103226,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -102613,13 +104952,13 @@ var ts; var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } @@ -103787,11 +106126,11 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -103806,7 +106145,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -103821,11 +106168,33 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertCommentThenNewline = function (sourceFile, character, position, commentText) { + var token = ts.getTouchingToken(sourceFile, position); + var text = "/**" + commentText + "*/" + this.newLineCharacter + ts.repeatString(" ", character); + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + ChangeTracker.prototype.tryInsertJSDocParameters = function (sourceFile, parameters) { + if (parameters.length === 0) { + return; + } + var parent = parameters[0].declaration.parent; + var indent = ts.getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; + var commentText = "\n"; + for (var _i = 0, parameters_3 = parameters; _i < parameters_3.length; _i++) { + var _a = parameters_3[_i], declaration = _a.declaration, typeNode = _a.typeNode, isOptional = _a.isOptional; + if (ts.isIdentifier(declaration.name)) { + var printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; + commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); + } + } + commentText += ts.repeatString(" ", indent + 1); + this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -103844,6 +106213,25 @@ var ts; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; + ChangeTracker.prototype.tryInsertJSDocType = function (sourceFile, node, type) { + var printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; + var commentText; + if (ts.isGetAccessorDeclaration(node)) { + commentText = " @return {" + printed + "} "; + } + else { + commentText = " @type {" + printed + "} "; + node = node.parent; + } + this.insertCommentThenNewline(sourceFile, ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); + }; + ChangeTracker.prototype.printJSDocParameter = function (indent, printed, name, isOptionalParameter) { + var printName = ts.unescapeLeadingUnderscores(name.escapedText); + if (isOptionalParameter) { + printName = "[" + printName + "]"; + } + return ts.repeatString(" ", indent) + (" * @param {" + printed + "} " + printName + "\n"); + }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); @@ -103887,30 +106275,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -103933,7 +106328,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104058,7 +106453,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104090,7 +106485,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104098,22 +106493,22 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; @@ -104172,9 +106567,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104200,14 +106602,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes); + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104245,9 +106651,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -105030,7 +107437,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105083,53 +107490,59 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } var _loop_10 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; @@ -105180,7 +107593,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105194,6 +107607,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105207,19 +107621,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105227,6 +107647,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105249,9 +107670,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105261,23 +107680,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105286,7 +107714,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105301,17 +107730,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105327,6 +107757,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105338,14 +107773,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105354,50 +107786,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105405,49 +107854,66 @@ var ts; refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_1 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_1 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105468,12 +107934,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105481,20 +107941,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105572,7 +108030,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -105689,7 +108147,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106175,33 +108633,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); 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, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106262,24 +108727,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, 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; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106321,7 +108786,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106369,17 +108834,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106389,7 +108850,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106397,11 +108873,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -106640,10 +109116,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -106682,7 +109158,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -106782,7 +109258,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -106792,7 +109268,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -106912,7 +109388,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -106922,24 +109400,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -107676,7 +110264,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -107808,22 +110396,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -107833,7 +110418,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -107931,38 +110516,35 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */ && token.kind !== 99 /* ThisKeyword */) { return undefined; } var parent = token.parent; @@ -107971,14 +110553,22 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + changes.tryInsertJSDocType(sourceFile, parent, typeNode); + } return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -107991,30 +110581,30 @@ var ts; switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); return param; } return undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -108022,9 +110612,9 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } function isApplicableFunctionForInference(declaration) { @@ -108038,36 +110628,62 @@ var ts; } return false; } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, host, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 151 /* PropertySignature */) { + changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var result = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + return typeNode && !param.initializer && !ts.getJSDocType(param) ? __assign({}, inference, { typeNode: typeNode }) : undefined; + }); + changes.tryInsertJSDocParameters(sourceFile, result); + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); var typeIsAccessible = true; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -108078,13 +110694,21 @@ var ts; reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; }); } function inferTypeForVariableFromUsage(token, program, cancellationToken) { @@ -108135,9 +110759,11 @@ var ts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; var isRest = ts.isRestParameter(parameter); + var isOptional = false; for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); continue; } if (isRest) { @@ -108150,10 +110776,14 @@ var ts; } } if (!types.length) { - return undefined; + return { declaration: parameter }; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -108381,16 +111011,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_1 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_1.set(name, symbol); }); } @@ -108406,17 +111038,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -108636,7 +111268,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -108662,6 +111294,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109757,7 +112589,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -109973,7 +112805,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110307,7 +113139,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110677,7 +113509,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -110809,7 +113641,7 @@ var ts; return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; @@ -111401,7 +114233,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112154,7 +114986,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112496,8 +115328,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112534,6 +115367,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112555,7 +115392,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -112670,7 +115507,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -112793,27 +115630,25 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113020,19 +115855,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -114826,6 +117673,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -114870,8 +117718,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -114946,7 +117794,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -115031,7 +117879,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -115160,71 +118008,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); //# sourceMappingURL=jsTyping.js.map "use strict"; var __assign = (this && this.__assign) || function () { @@ -115251,6 +118034,15 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; var ts; (function (ts) { var server; @@ -115453,12 +118245,13 @@ var ts; function isNonDuplicateInSortedArray(value, index, array) { return index === 0 || value !== array[index - 1]; } + var indentStr = "\n "; function indent(str) { - return "\n " + str; + return indentStr + str.replace(/\n/g, indentStr); } server.indent = indent; function stringifyIndented(json) { - return "\n " + JSON.stringify(json); + return indentStr + JSON.stringify(json); } server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); @@ -115699,7 +118492,7 @@ var ts; var text; var fileName = tempFileName || this.fileName; var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; - if (!ts.hasTypeScriptFileExtension(this.fileName)) { + if (!ts.hasTSFileExtension(this.fileName)) { var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > server.maxFileSize) { ts.Debug.assert(!!this.info.containingProjects.length); @@ -115983,6 +118776,7 @@ var ts; server.nullTypingsInstaller = { isKnownTypesPackageName: ts.returnFalse, installPackage: ts.notImplemented, + inspectValue: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -116042,6 +118836,9 @@ var ts; TypingsCache.prototype.installPackage = function (options) { return this.installer.installPackage(options); }; + TypingsCache.prototype.inspectValue = function (options) { + return this.installer.inspectValue(options); + }; TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -116159,6 +118956,7 @@ var ts; this.lastReportedVersion = 0; this.projectProgramVersion = 0; this.projectStateVersion = 0; + this.isInitialLoadPending = ts.returnFalse; this.dirty = false; this.hasChangedAutomaticTypeDirectiveNames = false; this.typingFiles = server.emptyArray; @@ -116219,6 +119017,9 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + Project.prototype.inspectValue = function (options) { + return this.typingsCache.inspectValue(options); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -116299,6 +119100,9 @@ var ts; Project.prototype.readFile = function (fileName) { return this.projectService.host.readFile(fileName); }; + Project.prototype.writeFile = function (fileName, content) { + return this.projectService.host.writeFile(fileName, content); + }; Project.prototype.fileExists = function (file) { var path = this.toPath(file); return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); @@ -116458,7 +119262,7 @@ var ts; var f = _a[_i]; this.detachScriptInfoIfNotRoot(f.fileName); } - var projectReferences = this.program.getProjectReferences(); + var projectReferences = this.program.getResolvedProjectReferences(); if (projectReferences) { for (var _b = 0, projectReferences_1 = projectReferences; _b < projectReferences_1.length; _b++) { var ref = projectReferences_1[_b]; @@ -116520,7 +119324,7 @@ var ts; return this.rootFiles; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { - var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; }); return scriptInfo; }); @@ -116812,7 +119616,9 @@ var ts; } }; Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - server.updateProjectIfDirty(this); + if (!this.isInitialLoadPending()) { + server.updateProjectIfDirty(this); + } var info = { projectName: this.getProjectName(), version: this.projectProgramVersion, @@ -116860,9 +119666,8 @@ var ts; ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); }; - Project.prototype.enableGlobalPlugins = function () { + Project.prototype.enableGlobalPlugins = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -116945,7 +119750,7 @@ var ts; if (!projectRootPath && !projectService.useSingleInferredProject) { _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory); } - _this.enableGlobalPlugins(); + _this.enableGlobalPlugins(_this.getCompilerOptions()); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -117017,27 +119822,36 @@ var ts; server.InferredProject = InferredProject; var ConfiguredProject = (function (_super) { __extends(ConfiguredProject, _super); - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { - var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; - _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectReferences = projectReferences; + function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, false, undefined, {}, false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.externalProjectRefCount = 0; + _this.isInitialLoadPending = ts.returnTrue; + _this.sendLoadingProjectFinish = false; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); - _this.enablePlugins(); return _this; } ConfiguredProject.prototype.updateGraph = function () { + this.isInitialLoadPending = ts.returnFalse; var reloadLevel = this.pendingReload; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + var result; switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: - return this.projectService.reloadFileNamesOfConfiguredProject(this); + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; case ts.ConfigFileProgramReloadLevel.Full: - this.projectService.reloadConfiguredProject(this); - return true; + var reason = ts.Debug.assertDefined(this.pendingReloadReason); + this.pendingReloadReason = undefined; + this.projectService.reloadConfiguredProject(this, reason); + result = true; + break; default: - return _super.prototype.updateGraph.call(this); + result = _super.prototype.updateGraph.call(this); } + this.projectService.sendProjectLoadingFinishEvent(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; }; ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { return this.directoryStructureHost; @@ -117053,11 +119867,13 @@ var ts; }; ConfiguredProject.prototype.getResolvedProjectReferences = function () { var program = this.getCurrentProgram(); - return program && program.getProjectReferences(); + return program && program.getResolvedProjectReferences(); }; ConfiguredProject.prototype.enablePlugins = function () { + this.enablePluginsWithOptions(this.getCompilerOptions()); + }; + ConfiguredProject.prototype.enablePluginsWithOptions = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117074,7 +119890,7 @@ var ts; this.enablePlugin(pluginConfigEntry, searchPaths); } } - this.enableGlobalPlugins(); + this.enableGlobalPlugins(options); }; ConfiguredProject.prototype.getGlobalProjectErrors = function () { return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; @@ -117131,16 +119947,14 @@ var ts; } return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; + ConfiguredProject.prototype.hasExternalProjectRef = function () { + return !!this.externalProjectRefCount; + }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; }; - ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (hasFileNames) { - if (hasFileNames) { - ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); - } - else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { - this.projectErrors.push(ts.getErrorForNoInputFiles(this.configFileSpecs, this.getConfigFilePath())); - } + ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) { + ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); }; return ConfiguredProject; }(Project)); @@ -117154,6 +119968,12 @@ var ts; _this.excludedFiles = []; return _this; } + ExternalProject.prototype.updateGraph = function () { + var result = _super.prototype.updateGraph.call(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; @@ -117179,6 +119999,9 @@ var ts; server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; server.maxFileSize = 4 * 1024 * 1024; server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.ProjectLoadingStartEvent = "projectLoadingStart"; + server.ProjectLoadingFinishEvent = "projectLoadingFinish"; + server.SurveyReady = "surveyReady"; server.LargeFileReferencedEvent = "largeFileReferenced"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -117266,6 +120089,11 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; + function convertUserPreferences(preferences) { + var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]); + return userPreferences; + } + server.convertUserPreferences = convertUserPreferences; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -117308,6 +120136,7 @@ var ts; WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; WatchType["TypeRoots"] = "Type root directory"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; })(WatchType = server.WatchType || (server.WatchType = {})); var ConfigFileWatcherStatus; (function (ConfigFileWatcherStatus) { @@ -117325,14 +120154,23 @@ var ts; function getDetailWatchInfo(watchType, project) { return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== undefined; + } function updateProjectIfDirty(project) { return project.dirty && project.updateGraph(); } server.updateProjectIfDirty = updateProjectIfDirty; + function setProjectOptionsUsed(project) { + if (project.projectKind === server.ProjectKind.Configured) { + project.projectOptions = true; + } + } var ProjectService = (function () { function ProjectService(opts) { var _this = this; this.filenameToScriptInfo = ts.createMap(); + this.scriptInfoInNodeModulesWatchers = ts.createMap(); this.filenameToScriptInfoVersion = ts.createMap(); this.allJsFilesForOpenFileTelemetry = ts.createMap(); this.externalProjectToConfiguredProjectMap = ts.createMap(); @@ -117345,9 +120183,10 @@ var ts; this.projectToSizeMap = ts.createMap(); this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist = ts.createMap(); this.pendingProjectUpdates = ts.createMap(); this.seenProjects = ts.createMap(); + this.seenSurveyProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -117360,7 +120199,7 @@ var ts; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; this.syntaxOnly = opts.syntaxOnly; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); if (this.host.realpath) { @@ -117440,14 +120279,14 @@ var ts; this.safelist = raw.typesMap; for (var key in raw.simpleMap) { if (raw.simpleMap.hasOwnProperty(key)) { - this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); } } } catch (e) { this.logger.info("Error loading types map: " + e); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist.clear(); } }; ProjectService.prototype.updateTypingsForProject = function (response) { @@ -117507,6 +120346,12 @@ var ts; }; this.eventHandler(event); }; + ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } }); + }; ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { if (!this.eventHandler) { return; @@ -117517,6 +120362,28 @@ var ts; }; this.eventHandler(event); }; + ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + var event = { + eventName: server.ProjectLoadingStartEvent, + data: { project: project, reason: reason } + }; + this.eventHandler(event); + }; + ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + project.sendLoadingProjectFinish = false; + var event = { + eventName: server.ProjectLoadingFinishEvent, + data: { project: project } + }; + this.eventHandler(event); + }; ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) { this.delayUpdateProjectGraph(project); this.delayEnsureProjectForOpenFiles(); @@ -117673,6 +120540,7 @@ var ts; else { this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files"); project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = "Change in config file detected"; this.delayUpdateProjectGraph(project); this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, true); } @@ -118011,33 +120879,6 @@ var ts; ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { return findProjectByName(projectFileName, this.externalProjects); }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { - configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); - var result = ts.parseJsonText(configFilename, configFileContent); - if (!result.endOfFileToken) { - result.endOfFileToken = { kind: 1 }; - } - var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); - if (parsedCommandLine.errors.length) { - errors.push.apply(errors, parsedCommandLine.errors); - } - ts.Debug.assert(!!parsedCommandLine.fileNames); - var projectOptions = { - files: parsedCommandLine.fileNames, - compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, - configHasFilesProperty: parsedCommandLine.raw.files !== undefined, - configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, - configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, - wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), - typeAcquisition: parsedCommandLine.typeAcquisition, - compileOnSave: parsedCommandLine.compileOnSave, - projectReferences: parsedCommandLine.projectReferences - }; - return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; - }; ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { return; @@ -118049,12 +120890,12 @@ var ts; for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var f = fileNames_1[_i]; var fileName = propertyReader.getFileName(f); - if (ts.hasTypeScriptFileExtension(fileName)) { + if (ts.hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); return fileName; } } @@ -118065,9 +120906,9 @@ var ts; return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); } function getTop5LargestFiles(_a) { - var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; + var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .filter(function (name) { return hasTypeScriptFileExtension(name); }) + .filter(function (name) { return hasTSFileExtension(name); }) .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) .sort(function (a, b) { return b.size - a.size; }) .slice(0, 5); @@ -118077,21 +120918,35 @@ var ts; var compilerOptions = convertCompilerOptions(options); var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); project.excludedFiles = excludedFiles; - this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); - this.sendProjectTelemetry(projectFileName, project); return project; }; - ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { - if (this.seenProjects.has(projectKey)) { + ProjectService.prototype.sendSurveyReady = function (project) { + if (this.seenSurveyProjects.has(project.projectName)) { return; } - this.seenProjects.set(projectKey, true); + if (project.getCompilerOptions().checkJs !== undefined) { + var name = "checkJs"; + this.logger.info("Survey " + name + " is ready"); + this.sendSurveyReadyEvent(name); + this.seenSurveyProjects.set(project.projectName, true); + } + }; + ProjectService.prototype.sendProjectTelemetry = function (project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); + return; + } + this.seenProjects.set(project.projectName, true); if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); return; } + var projectOptions = project.projectKind === server.ProjectKind.Configured ? project.projectOptions : undefined; + setProjectOptionsUsed(project); var data = { - projectId: this.host.createSHA256Hash(projectKey), + projectId: this.host.createSHA256Hash(project.projectName), fileStats: server.countEachFileTypes(project.getScriptInfos()), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), @@ -118110,8 +120965,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; - return server.getBaseConfigFileName(configFilePath) || "other"; + return server.getBaseConfigFileName(project.getConfigFilePath()) || "other"; } function convertTypeAcquisition(_a) { var enable = _a.enable, include = _a.include, exclude = _a.exclude; @@ -118122,31 +120976,76 @@ var ts; }; } }; - ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { + ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) { this.updateNonInferredProjectFiles(project, files, propertyReader); project.setTypeAcquisition(typeAcquisition); - project.updateGraph(); }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); - var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); - project.configFileSpecs = configFileSpecs; + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program", project); - if (!lastFileExceededProgramSize) { - project.watchWildcards(projectOptions.wildcardDirectories); - } - project.setProjectErrors(configFileErrors); - var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); - this.sendProjectTelemetry(configFileName, project, projectOptions); return project; }; + ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; + return project; + }; + ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project, reason); + return project; + }; + ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) { + var project = this.createAndLoadConfiguredProject(configFileName, reason); + project.updateGraph(); + return project; + }; + ProjectService.prototype.loadConfiguredProject = function (project, reason) { + this.sendProjectLoadingStartEvent(project, reason); + var configFilename = ts.normalizePath(project.getConfigFilePath()); + var configFileContent = this.host.readFile(configFilename); + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 }; + } + var configFileErrors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + var compilerOptions = parsedCommandLine.options; + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + }; + } + project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(parsedCommandLine.raw); + project.setProjectErrors(configFileErrors); + project.updateReferences(parsedCommandLine.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + project.stopWatchingWildCards(); + } + else { + project.enableLanguageService(); + project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); + } + project.enablePluginsWithOptions(compilerOptions); + var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); + }; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = ts.createMap(); @@ -118194,40 +121093,28 @@ var ts; } project.markAsDirty(); }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { + ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } - this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { var configFileSpecs = project.configFileSpecs; var configFileName = project.getConfigFilePath(); var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); - project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); - this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); + project.updateErrorOnNoInputFiles(fileNamesResult); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); }; - ProjectService.prototype.reloadConfiguredProject = function (project) { + ProjectService.prototype.reloadConfiguredProject = function (project, reason) { var host = project.getCachedDirectoryStructureHost(); host.clearCache(); var configFileName = project.getConfigFilePath(); this.logger.info("Reloading configured project " + configFileName); - var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; - project.configFileSpecs = configFileSpecs; - project.setProjectErrors(configFileErrors); - project.updateReferences(projectOptions.projectReferences); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - if (lastFileExceededProgramSize) { - project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - } - else { - project.enableLanguageService(); - project.watchWildcards(projectOptions.wildcardDirectories); - } - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); + this.loadConfiguredProject(project, reason); + project.updateGraph(); this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { @@ -118354,10 +121241,77 @@ var ts; if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - var fileName = info.fileName; - info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); + var indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } } }; + ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) { + var _this = this; + var existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + var watchDir = dir + "/node_modules"; + var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + ts.Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + _this.refreshScriptInfosInDirectory(watchDir); + } + else { + var info = _this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + _this.refreshScriptInfo(info); + } + } + else if (!ts.hasExtension(fileOrDirectoryPath)) { + _this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, 1, "node_modules for closed script infos in them"); + var result = { + close: function () { + if (result.refCount === 1) { + watcher.close(); + _this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + }; + ProjectService.prototype.getModifiedTime = function (info) { + return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime(); + }; + ProjectService.prototype.refreshScriptInfo = function (info) { + var mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + }; + ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) { + var _this = this; + dir = dir + ts.directorySeparator; + this.filenameToScriptInfo.forEach(function (info) { + if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) { + _this.refreshScriptInfo(info); + } + }); + }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { if (info.fileWatcher) { info.fileWatcher.close(); @@ -118416,6 +121370,7 @@ var ts; return this.filenameToScriptInfo.get(fileName); }; ProjectService.prototype.setHostConfiguration = function (args) { + var _this = this; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { @@ -118433,7 +121388,17 @@ var ts; this.logger.info("Format host information updated"); } if (args.preferences) { + var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject; this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences); + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + this.configuredProjects.forEach(function (project) { + if (project.hasExternalProjectRef() && + project.pendingReload === ts.ConfigFileProgramReloadLevel.Full && + !_this.pendingProjectUpdates.has(project.getProjectName())) { + project.updateGraph(); + } + }); + } } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; @@ -118447,16 +121412,16 @@ var ts; }; ProjectService.prototype.reloadProjects = function () { this.logger.info("reload projects."); - this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue); + this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue, "User requested reload projects"); this.ensureProjectForOpenFiles(); }; ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, true, ignoreIfNotRootOfInferredProject ? function (isRootOfInferredProject) { return isRootOfInferredProject; } : - ts.returnTrue); + ts.returnTrue, "Change in config file detected"); this.delayEnsureProjectForOpenFiles(); }; - ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor) { + ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) { var _this = this; var updatedProjects = ts.createMap(); openFiles.forEach(function (openFileValue, path) { @@ -118467,18 +121432,15 @@ var ts; ts.Debug.assert(info.isScriptOpen()); var configFileName = _this.getConfigFileNameForFile(info); if (configFileName) { - var project = _this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - _this.createConfiguredProject(configFileName); - updatedProjects.set(configFileName, true); - } - else if (!updatedProjects.has(configFileName)) { + var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName); + if (!updatedProjects.has(configFileName)) { if (delayReload) { project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; _this.delayUpdateProjectGraph(project); } else { - _this.reloadConfiguredProject(project); + _this.reloadConfiguredProject(project, reason); } updatedProjects.set(configFileName, true); } @@ -118527,7 +121489,8 @@ var ts; var configFileName = this.getConfigFileNameForFile(originalFileInfo); if (!configFileName) return undefined; - var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || + this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName); updateProjectIfDirty(configuredProject); addOriginalConfiguredProject(configuredProject); var originalScriptInfo = this.getScriptInfo(fileName); @@ -118567,7 +121530,7 @@ var ts; if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createConfiguredProject(configFileName); + project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open"); if (info.isOrphan()) { configFileName = undefined; } @@ -118825,11 +121788,11 @@ var ts; if (ts.fileExtensionIs(baseName, "js")) { var inferredTypingName = ts.removeFileExtension(baseName); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - if (this_3.legacySafelist[cleanedTypingName]) { + var typeName = this_3.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); excludedFiles.push(normalizedNames[i]); exclude = true; - var typeName = this_3.legacySafelist[cleanedTypingName]; if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); } @@ -118895,7 +121858,8 @@ var ts; else { externalProject.enableLanguageService(); } - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + externalProject.updateGraph(); return; } this.closeExternalProject(proj.projectFileName); @@ -118935,7 +121899,9 @@ var ts; var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { - project = this.createConfiguredProject(tsconfigFile); + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? + this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { project.addExternalProjectReference(); @@ -118944,7 +121910,8 @@ var ts; } else { this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); } }; ProjectService.prototype.hasDeferredExtension = function () { @@ -119137,7 +122104,7 @@ var ts; }; } server.toEvent = toEvent; - function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { + function combineProjectOutput(defaultValue, getValue, projects, action) { var outputs = ts.flatMap(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); if (!ts.isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach(function (projects, path) { @@ -119145,9 +122112,7 @@ var ts; outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); }); } - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); + return ts.deduplicate(outputs, ts.equateValues); } function combineProjectOutputFromEveryProject(projectService, action, areEqual) { var outputs = []; @@ -119190,17 +122155,19 @@ var ts; } function combineProjectOutputForReferences(projects, defaultProject, initialLocation, projectService) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, getMappedLocation) { var project = _a.project, location = _a.location; var _loop_8 = function (outputReferencedSymbol) { - var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, outputReferencedSymbol.definition); }); + var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.position, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); if (!symbolToAddTo) { - symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + symbolToAddTo = { definition: definition, references: [] }; outputs.push(symbolToAddTo); } for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { var ref = _a[_i]; - if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { symbolToAddTo.references.push(ref); } } @@ -119261,7 +122228,7 @@ var ts; seenProjects.set(projectAndLocation.project.projectName, true); var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); if (!originalLocation) - return false; + return undefined; var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); toDo = toDo || []; for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { @@ -119277,7 +122244,7 @@ var ts; } }); } - return true; + return originalLocation; }); return toDo; } @@ -119632,6 +122599,7 @@ var ts; globalPlugins: opts.globalPlugins, pluginProbeLocations: opts.pluginProbeLocations, allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, syntaxOnly: opts.syntaxOnly, }; this.projectService = new server.ProjectService(settings); @@ -119646,21 +122614,33 @@ var ts; var openFiles = event.data.openFiles; this.projectsUpdatedInBackgroundEvent(openFiles); break; + case server.ProjectLoadingStartEvent: + var _a = event.data, project = _a.project, reason = _a.reason; + this.event({ projectName: project.getProjectName(), reason: reason }, server.ProjectLoadingStartEvent); + break; + case server.ProjectLoadingFinishEvent: + var finishProject = event.data.project; + this.event({ projectName: finishProject.getProjectName() }, server.ProjectLoadingStartEvent); + break; case server.LargeFileReferencedEvent: - var _a = event.data, file = _a.file, fileSize = _a.fileSize, maxFileSize_1 = _a.maxFileSize; - this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, "largeFileReferenced"); + var _b = event.data, file = _b.file, fileSize = _b.fileSize, maxFileSize_1 = _b.maxFileSize; + this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, server.LargeFileReferencedEvent); break; case server.ConfigFileDiagEvent: - var _b = event.data, triggerFile = _b.triggerFile, configFile = _b.configFileName, diagnostics = _b.diagnostics; + var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics; var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); this.event({ triggerFile: triggerFile, configFile: configFile, diagnostics: bakedDiags - }, "configFileDiag"); + }, server.ConfigFileDiagEvent); + break; + case server.SurveyReady: + var surveyId = event.data.surveyId; + this.event({ surveyId: surveyId }, server.SurveyReady); break; case server.ProjectLanguageServiceStateEvent: { - var eventName = "projectLanguageServiceState"; + var eventName = server.ProjectLanguageServiceStateEvent; this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled @@ -119687,10 +122667,13 @@ var ts; } this.event({ openFiles: openFiles - }, "projectsUpdatedInBackground"); + }, server.ProjectsUpdatedInBackgroundEvent); } }; Session.prototype.logError = function (err, cmd) { + this.logErrorWorker(err, cmd); + }; + Session.prototype.logErrorWorker = function (err, cmd, fileRequest) { var msg = "Exception on executing command " + cmd; if (err.message) { msg += ":\n" + server.indent(err.message); @@ -119698,6 +122681,17 @@ var ts; msg += "\n" + server.indent(err.stack); } } + if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) { + try { + var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + var text = ts.getSnapshotText(scriptInfo.getSnapshot()); + msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + } + } + catch (_b) { } + } this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { @@ -120136,21 +123130,28 @@ var ts; if (!simplifiedResult) return locations; var defaultProject = this.getDefaultProject(args); - var renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; - Session.mapRenameInfo = function (_a) { - var canRename = _a.canRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers; - return { canRename: canRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers }; + Session.prototype.mapRenameInfo = function (info, scriptInfo) { + if (info.canRename) { + var canRename = info.canRename, fileToRename = info.fileToRename, displayName = info.displayName, fullDisplayName = info.fullDisplayName, kind = info.kind, kindModifiers = info.kindModifiers, triggerSpan = info.triggerSpan; + return ts.identity({ canRename: canRename, fileToRename: fileToRename, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }); + } + else { + return info; + } }; Session.prototype.toSpanGroups = function (locations) { var map = ts.createMap(); for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { - var _a = locations_1[_i], fileName = _a.fileName, textSpan = _a.textSpan; + var _a = locations_1[_i]; + var fileName = _a.fileName, textSpan = _a.textSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "originalTextSpan", "originalFileName"]); var group_1 = map.get(fileName); if (!group_1) map.set(fileName, group_1 = { file: fileName, locs: [] }); - group_1.locs.push(this.toLocationTextSpan(textSpan, ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)))); + var scriptInfo = ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)); + group_1.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText)); } return ts.arrayFrom(map.values()); }; @@ -120368,7 +123369,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); if (completions === undefined) return undefined; if (kind === "completions-full") @@ -120708,8 +123709,8 @@ var ts; var commands = args.command; for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; - var project = this.getFileAndProject(command).project; - project.getLanguageService().applyCodeActionCommand(command).then(function (_result) { }, function (_error) { }); + var _b = this.getFileAndProject(command), file = _b.file, project = _b.project; + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { }); } return {}; }; @@ -120864,8 +123865,10 @@ var ts; } } var request; + var relevantFile; try { request = JSON.parse(message); + relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; if (this.logger.hasLevel(server.LogLevel.requestTime)) { var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); @@ -120888,7 +123891,7 @@ var ts; this.doOutput({ canceled: true }, request.command, request.seq, true); return; } - this.logError(err, message); + this.logErrorWorker(err, message, relevantFile); this.doOutput(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, false, "Error processing request. " + err.message + "\n" + err.stack); } }; @@ -121840,13 +124843,18 @@ var ts; }; NodeTypingsInstaller.prototype.installPackage = function (options) { var _this = this; - var rq = __assign({ kind: "installPackage" }, options); - this.send(rq); + this.send(__assign({ kind: "installPackage" }, options)); ts.Debug.assert(this.packageInstalledPromise === undefined); return new Promise(function (resolve, reject) { _this.packageInstalledPromise = { resolve: resolve, reject: reject }; }); }; + NodeTypingsInstaller.prototype.inspectValue = function (options) { + var _this = this; + this.send({ kind: "inspectValue", options: options }); + ts.Debug.assert(this.inspectValuePromise === undefined); + return new Promise(function (resolve) { _this.inspectValuePromise = { resolve: resolve }; }); + }; NodeTypingsInstaller.prototype.attach = function (projectService) { var _this = this; this.projectService = projectService; @@ -121945,6 +124953,10 @@ var ts; this.event(response, "setTypings"); break; } + case server.ActionValueInspected: + this.inspectValuePromise.resolve(response.result); + this.inspectValuePromise = undefined; + break; case server.EventInitializationFailed: { var body = { @@ -122071,6 +125083,7 @@ var ts; globalPlugins: globalPlugins, pluginProbeLocations: pluginProbeLocations, allowLocalPluginLoads: allowLocalPluginLoads, + typesMapLocation: typesMapLocation, }) || this; _this.eventPort = eventPort; if (_this.canUseEvents && _this.eventPort) { @@ -122190,13 +125203,16 @@ var ts; var cmdLineLogFileName = server.findArgument("--logFile"); var cmdLineVerbosity = getLogLevel(server.findArgument("--logVerbosity")); var envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); - var logFileName = cmdLineLogFileName + var unsubstitutedLogFileName = cmdLineLogFileName ? ts.stripQuotes(cmdLineLogFileName) : envLogOptions.logToFile ? envLogOptions.file || (__dirname + "/.log" + process.pid.toString()) : undefined; + var substitutedLogFileName = unsubstitutedLogFileName + ? unsubstitutedLogFileName.replace("PID", process.pid.toString()) + : undefined; var logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel; - return new Logger(logFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217 + return new Logger(substitutedLogFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217 } // This places log file in the directory containing editorServices.js // TODO: check that this location is writable @@ -122414,7 +125430,7 @@ var ts; } sys.require = function (initialDir, moduleName) { try { - return { module: require(ts.resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; + return { module: require(ts.resolveJSModule(moduleName, initialDir, sys)), error: undefined }; } catch (error) { return { module: undefined, error: error }; @@ -122442,7 +125458,7 @@ var ts; } ts.setStackTraceLimit(); var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); // TODO: GH#18217 - var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(sys.getExecutingFilePath(), "../typesMap.json"); + var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(ts.getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); var npmLocation = server.findArgument(server.Arguments.NpmLocation); function parseStringArray(argName) { var arg = server.findArgument(argName); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index a16288c6c27..d8306559986 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ const version: string; } @@ -69,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -536,6 +537,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +634,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +671,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -1079,7 +1083,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1808,7 +1812,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -2056,32 +2061,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2490,6 +2495,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2587,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2597,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2698,9 +2695,6 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -3001,6 +2995,16 @@ declare namespace ts { Parameters = 1296, IndexSignatureParameters = 4432 } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3209,17 +3213,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -4171,14 +4185,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4318,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4361,14 +4387,6 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; } /** * Host to create watch with root files and options @@ -4378,6 +4396,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4432,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,184 +4443,11 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4609,7 +4456,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4817,14 +4664,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4882,9 +4722,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5046,9 +4886,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5114,6 +4961,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5266,15 +5115,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; @@ -5751,24 +5609,6 @@ declare namespace ts.server { remove(path: NormalizedPath): void; } function createNormalizedPathMap(): NormalizedPathMap; - interface ProjectOptions { - configHasExtendsProperty: boolean; - /** - * true if config file explicitly listed files - */ - configHasFilesProperty: boolean; - configHasIncludeProperty: boolean; - configHasExcludeProperty: boolean; - projectReferences: ReadonlyArray | undefined; - /** - * these fields can be present in the project file - */ - files?: string[]; - wildcardDirectories?: Map; - compilerOptions?: CompilerOptions; - typeAcquisition?: TypeAcquisition; - compileOnSave?: boolean; - } function isInferredProjectName(name: string): boolean; function makeInferredProjectName(counter: number): string; function createSortedArray(): SortedArray; @@ -6602,15 +6442,17 @@ declare namespace ts.server.protocol { /** * Information about the item to be renamed. */ - interface RenameInfo { + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { /** * True if item can be renamed. */ - canRename: boolean; + canRename: true; /** - * Error message if item can not be renamed. + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ - localizedErrorMessage?: string; + fileToRename?: string; /** * Display name of the item to be renamed. */ @@ -6627,6 +6469,15 @@ declare namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; } /** * A group of text spans, all in 'file'. @@ -6635,7 +6486,11 @@ declare namespace ts.server.protocol { /** The file to which the spans apply */ file: string; /** The text spans in this group */ - locs: TextSpan[]; + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface RenameResponseBody { /** @@ -7148,7 +7003,7 @@ declare namespace ts.server.protocol { * begin with prefix. */ interface CompletionsRequest extends FileLocationRequest { - command: CommandTypes.Completions; + command: CommandTypes.Completions | CommandTypes.CompletionInfo; arguments: CompletionsRequestArgs; } /** @@ -7660,6 +7515,35 @@ declare namespace ts.server.protocol { */ openFiles: string[]; } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } type LargeFileReferencedEventName = "largeFileReferenced"; interface LargeFileReferencedEvent extends Event { event: LargeFileReferencedEventName; @@ -7995,6 +7879,7 @@ declare namespace ts.server.protocol { readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -8126,14 +8011,14 @@ declare namespace ts.server { getSnapshot(): IScriptSnapshot; private ensureRealPath; getFormatCodeSettings(): FormatCodeSettings | undefined; - getPreferences(): UserPreferences | undefined; + getPreferences(): protocol.UserPreferences | undefined; attachToProject(project: Project): boolean; isAttached(project: Project): boolean; detachFromProject(project: Project): void; detachAllProjects(): void; getDefaultProject(): Project; registerFileUpdate(): void; - setOptions(formatSettings: FormatCodeSettings, preferences: UserPreferences | undefined): void; + setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void; getLatestVersion(): string; saveTo(fileName: string): void; reloadFromFile(tempFileName?: NormalizedPath): boolean; @@ -8238,6 +8123,7 @@ declare namespace ts.server { * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project */ private projectStateVersion; + protected isInitialLoadPending: () => boolean; private readonly cancellationToken; isNonTsProject(): boolean; isJsOnlyProject(): boolean; @@ -8261,6 +8147,7 @@ declare namespace ts.server { useCaseSensitiveFileNames(): boolean; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile(fileName: string): string | undefined; + writeFile(fileName: string, content: string): void; fileExists(file: string): boolean; resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[]; getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; @@ -8322,7 +8209,7 @@ declare namespace ts.server { filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; protected removeRoot(info: ScriptInfo): void; - protected enableGlobalPlugins(): void; + protected enableGlobalPlugins(options: CompilerOptions): void; protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ refreshDiagnostics(): void; @@ -8351,14 +8238,14 @@ declare namespace ts.server { * Otherwise it will create an InferredProject. */ class ConfiguredProject extends Project { - compileOnSaveEnabled: boolean; - private projectReferences; private typeAcquisition; private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; /** Ref count to the project when opened from external project */ private externalProjectRefCount; private projectErrors; + private projectReferences; + protected isInitialLoadPending: () => boolean; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph * @returns: true if set of files in the project stays the same and false - otherwise. @@ -8391,6 +8278,7 @@ declare namespace ts.server { compileOnSaveEnabled: boolean; excludedFiles: ReadonlyArray; private typeAcquisition; + updateGraph(): boolean; getExcludedFiles(): ReadonlyArray; getTypeAcquisition(): TypeAcquisition; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; @@ -8399,6 +8287,9 @@ declare namespace ts.server { declare namespace ts.server { const maxProgramSizeForNonTsFiles: number; const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + const ProjectLoadingStartEvent = "projectLoadingStart"; + const ProjectLoadingFinishEvent = "projectLoadingFinish"; + const SurveyReady = "surveyReady"; const LargeFileReferencedEvent = "largeFileReferenced"; const ConfigFileDiagEvent = "configFileDiag"; const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -8410,6 +8301,25 @@ declare namespace ts.server { openFiles: string[]; }; } + interface ProjectLoadingStartEvent { + eventName: typeof ProjectLoadingStartEvent; + data: { + project: Project; + reason: string; + }; + } + interface ProjectLoadingFinishEvent { + eventName: typeof ProjectLoadingFinishEvent; + data: { + project: Project; + }; + } + interface SurveyReady { + eventName: typeof SurveyReady; + data: { + surveyId: string; + }; + } interface LargeFileReferencedEvent { eventName: typeof LargeFileReferencedEvent; data: { @@ -8488,7 +8398,7 @@ declare namespace ts.server { interface OpenFileInfo { readonly checkJs: boolean; } - type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; interface SafeList { [name: string]: { @@ -8509,7 +8419,7 @@ declare namespace ts.server { function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; interface HostConfiguration { formatCodeOptions: FormatCodeSettings; - preferences: UserPreferences; + preferences: protocol.UserPreferences; hostInfo: string; extraFileExtensions?: FileExtensionInfo[]; } @@ -8538,6 +8448,7 @@ declare namespace ts.server { * Container of all known scripts */ private readonly filenameToScriptInfo; + private readonly scriptInfoInNodeModulesWatchers; /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -8586,7 +8497,7 @@ declare namespace ts.server { private readonly throttledOperations; private readonly hostConfiguration; private safelist; - private legacySafelist; + private readonly legacySafelist; private pendingProjectUpdates; readonly currentDirectory: NormalizedPath; readonly toCanonicalFileName: (f: string) => string; @@ -8607,6 +8518,8 @@ declare namespace ts.server { readonly syntaxOnly?: boolean; /** Tracks projects that we have already sent telemetry for. */ private readonly seenProjects; + /** Tracks projects that we have already sent survey events for. */ + private readonly seenSurveyProjects; constructor(opts: ProjectServiceOptions); toPath(fileName: string): Path; private loadTypesMap; @@ -8628,9 +8541,9 @@ declare namespace ts.server { */ private ensureProjectStructuresUptoDate; getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; - getPreferences(file: NormalizedPath): UserPreferences; + getPreferences(file: NormalizedPath): protocol.UserPreferences; getHostFormatCodeOptions(): FormatCodeSettings; - getHostPreferences(): UserPreferences; + getHostPreferences(): protocol.UserPreferences; private onSourceFileChanged; private handleDeletedFile; private onConfigChangedForConfiguredProject; @@ -8692,15 +8605,13 @@ declare namespace ts.server { private findConfiguredProjectByProjectName; private getConfiguredProjectByCanonicalConfigFilePath; private findExternalProjectByProjectName; - private convertConfigFileContentToProjectOptions; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ private getFilenameForExceededTotalSizeLimitForNonTsFiles; private createExternalProject; - private sendProjectTelemetry; - private addFilesToNonInferredProjectAndUpdateGraph; + private addFilesToNonInferredProject; private createConfiguredProject; private updateNonInferredProjectFiles; - private updateNonInferredProject; + private updateRootAndOptionsOfNonInferredProject; private sendConfigFileDiagEvent; private getOrCreateInferredProjectForProjectRootPathIfEnabled; private getOrCreateSingleInferredProjectIfEnabled; @@ -8708,6 +8619,10 @@ declare namespace ts.server { private createInferredProject; getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; private watchClosedScriptInfo; + private watchClosedScriptInfoInNodeModules; + private getModifiedTime; + private refreshScriptInfo; + private refreshScriptInfosInDirectory; private stopWatchingScriptInfo; private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; private getOrCreateScriptInfoOpenedByClientForNormalizedPath; @@ -8815,6 +8730,7 @@ declare namespace ts.server { globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; + typesMapLocation?: string; } class Session implements EventSender { private readonly gcTimer; @@ -8837,6 +8753,7 @@ declare namespace ts.server { private defaultEventHandler; private projectsUpdatedInBackgroundEvent; logError(err: Error, cmd: string): void; + private logErrorWorker; send(msg: protocol.Message): void; event(body: T, eventName: string): void; /** @deprecated */ @@ -8881,7 +8798,7 @@ declare namespace ts.server { private getProjects; private getDefaultProject; private getRenameLocations; - private static mapRenameInfo; + private mapRenameInfo; private toSpanGroups; private getReferences; /** diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 19046c62c9a..53d751f50a5 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -62,18 +62,27 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -88,6 +97,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -716,17 +726,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -771,7 +787,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1148,7 +1164,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1284,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1432,7 +1452,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1935,6 +1957,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2029,6 +2055,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2615,6 +3001,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2665,6 +3052,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2734,38 +3123,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2840,14 +3229,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2993,9 +3383,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3403,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3266,25 +3655,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3303,25 +3688,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3565,20 +3949,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3796,17 +4166,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4127,11 +4501,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4742,7 +5117,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5156,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5024,7 +5403,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5430,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5529,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5643,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5739,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5837,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5876,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5545,6 +5943,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5673,10 +6072,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { return token >= 71 /* Identifier */; @@ -5687,136 +6089,85 @@ var ts; return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 117 /* AbstractKeyword */, + any: 119 /* AnyKeyword */, + as: 118 /* AsKeyword */, + boolean: 122 /* BooleanKeyword */, + break: 72 /* BreakKeyword */, + case: 73 /* CaseKeyword */, + catch: 74 /* CatchKeyword */, + class: 75 /* ClassKeyword */, + continue: 77 /* ContinueKeyword */, + const: 76 /* ConstKeyword */ + }, + _a["" + "constructor"] = 123 /* ConstructorKeyword */, + _a.debugger = 78 /* DebuggerKeyword */, + _a.declare = 124 /* DeclareKeyword */, + _a.default = 79 /* DefaultKeyword */, + _a.delete = 80 /* DeleteKeyword */, + _a.do = 81 /* DoKeyword */, + _a.else = 82 /* ElseKeyword */, + _a.enum = 83 /* EnumKeyword */, + _a.export = 84 /* ExportKeyword */, + _a.extends = 85 /* ExtendsKeyword */, + _a.false = 86 /* FalseKeyword */, + _a.finally = 87 /* FinallyKeyword */, + _a.for = 88 /* ForKeyword */, + _a.from = 143 /* FromKeyword */, + _a.function = 89 /* FunctionKeyword */, + _a.get = 125 /* GetKeyword */, + _a.if = 90 /* IfKeyword */, + _a.implements = 108 /* ImplementsKeyword */, + _a.import = 91 /* ImportKeyword */, + _a.in = 92 /* InKeyword */, + _a.infer = 126 /* InferKeyword */, + _a.instanceof = 93 /* InstanceOfKeyword */, + _a.interface = 109 /* InterfaceKeyword */, + _a.is = 127 /* IsKeyword */, + _a.keyof = 128 /* KeyOfKeyword */, + _a.let = 110 /* LetKeyword */, + _a.module = 129 /* ModuleKeyword */, + _a.namespace = 130 /* NamespaceKeyword */, + _a.never = 131 /* NeverKeyword */, + _a.new = 94 /* NewKeyword */, + _a.null = 95 /* NullKeyword */, + _a.number = 134 /* NumberKeyword */, + _a.object = 135 /* ObjectKeyword */, + _a.package = 111 /* PackageKeyword */, + _a.private = 112 /* PrivateKeyword */, + _a.protected = 113 /* ProtectedKeyword */, + _a.public = 114 /* PublicKeyword */, + _a.readonly = 132 /* ReadonlyKeyword */, + _a.require = 133 /* RequireKeyword */, + _a.global = 144 /* GlobalKeyword */, + _a.return = 96 /* ReturnKeyword */, + _a.set = 136 /* SetKeyword */, + _a.static = 115 /* StaticKeyword */, + _a.string = 137 /* StringKeyword */, + _a.super = 97 /* SuperKeyword */, + _a.switch = 98 /* SwitchKeyword */, + _a.symbol = 138 /* SymbolKeyword */, + _a.this = 99 /* ThisKeyword */, + _a.throw = 100 /* ThrowKeyword */, + _a.true = 101 /* TrueKeyword */, + _a.try = 102 /* TryKeyword */, + _a.type = 139 /* TypeKeyword */, + _a.typeof = 103 /* TypeOfKeyword */, + _a.undefined = 140 /* UndefinedKeyword */, + _a.unique = 141 /* UniqueKeyword */, + _a.unknown = 142 /* UnknownKeyword */, + _a.var = 104 /* VarKeyword */, + _a.void = 105 /* VoidKeyword */, + _a.while = 106 /* WhileKeyword */, + _a.with = 107 /* WithKeyword */, + _a.yield = 116 /* YieldKeyword */, + _a.async = 120 /* AsyncKeyword */, + _a.await = 121 /* AwaitKeyword */, + _a.of = 145 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, ">": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -6394,6 +6745,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6423,6 +6775,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6820,9 +7173,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -6878,6 +7231,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7270,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6973,6 +7345,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7478,7 +7855,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7555,6 +7932,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +7955,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7657,22 +8036,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8143,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8001,12 +8373,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,13 +8413,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8408,6 +8788,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8468,6 +8852,7 @@ var ts; case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: case 138 /* SymbolKeyword */: + case 135 /* ObjectKeyword */: case 140 /* UndefinedKeyword */: case 131 /* NeverKeyword */: return true; @@ -9135,18 +9520,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9186,14 +9571,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9216,15 +9601,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9232,26 +9621,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,7 +9649,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9274,30 +9663,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9308,7 +9697,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9352,12 +9741,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9367,9 +9756,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9398,7 +9787,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,11 +9796,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9517,7 +9906,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9559,6 +9948,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9749,6 +10142,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9773,32 +10172,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9857,7 +10260,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10269,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10600,7 +11003,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10614,7 +11017,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10735,7 +11138,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11154,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11035,13 +11438,18 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -11063,15 +11471,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } @@ -11107,10 +11506,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11249,6 +11648,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +11760,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11514,6 +11937,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11525,12 +11950,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11756,13 +12203,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12090,13 +12530,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12108,9 +12548,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12118,10 +12556,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12152,7 +12588,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12198,15 +12634,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12662,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12353,7 +12805,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13699,7 +14164,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14092,6 +14557,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14585,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14598,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14401,8 +14878,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15099,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14684,6 +15166,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14910,36 +15393,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15067,14 +15571,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +15749,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -15333,6 +15853,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15403,6 +15924,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15761,7 +16283,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16452,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -16599,7 +17125,15 @@ var ts; // which would be a candidate for improved error reporting. return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 21 /* OpenBracketToken */: + case 39 /* AsteriskToken */: + case 24 /* DotDotDotToken */: + case 23 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: @@ -17367,8 +17901,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19464,8 +20000,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -20866,7 +21403,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -20991,13 +21528,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21012,7 +21542,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21083,7 +21615,7 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -21264,10 +21796,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21281,14 +21811,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21376,7 +21906,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21391,7 +21921,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21452,7 +21982,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21492,17 +22022,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21530,7 +22060,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21556,9 +22086,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -22399,8 +22927,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +22941,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22461,21 +23024,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22490,6 +23038,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23058,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23071,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23079,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23097,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23207,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23216,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23225,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23251,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23260,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23294,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23307,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23315,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23325,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23341,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23353,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23364,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22874,30 +23449,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23513,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23533,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23579,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23587,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23615,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23643,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +23734,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +23784,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +23804,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +23812,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +23848,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +23891,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +23916,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23619,7 +24258,11 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -23926,7 +24569,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24587,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23980,19 +24638,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +24657,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +24670,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24110,11 +24782,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24161,7 +24828,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +24836,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25050,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24408,10 +25075,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24421,9 +25093,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24431,7 +25119,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24442,16 +25130,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24640,6 +25328,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24656,7 +25350,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25359,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24750,7 +25490,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24770,7 +25511,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24797,11 +25537,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,7 +25557,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24856,14 +25603,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -25086,15 +25837,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +25883,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +25902,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,74 +25913,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25241,8 +25978,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25250,7 +25987,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +26001,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +26018,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,7 +26049,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25352,52 +26090,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25411,12 +26143,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26162,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26200,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,51 +26212,56 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25550,87 +26281,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26411,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,43 +26424,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25695,24 +26469,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26501,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25944,13 +26718,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -25995,7 +26773,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26075,7 +26853,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26153,12 +26932,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26321,6 +27100,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -26419,6 +27199,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -26821,7 +27603,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -27217,7 +27998,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +28018,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27325,9 +28106,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27347,7 +28125,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27572,7 +28350,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27619,7 +28397,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27636,15 +28414,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27717,15 +28495,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27741,7 +28519,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27752,9 +28530,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27835,37 +28613,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27901,7 +28677,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27931,7 +28707,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -27988,7 +28764,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28009,7 +28785,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28035,40 +28811,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,7 +28852,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28090,7 +28865,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28174,8 +28949,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,10 +28965,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28207,7 +28985,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +29003,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,10 +29044,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28278,14 +29056,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28304,9 +29082,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,7 +29120,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(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; })); } @@ -28382,6 +29158,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28457,40 +29236,40 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28511,7 +29290,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28522,25 +29301,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28575,35 +29354,35 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28621,7 +29400,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28632,7 +29411,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28644,7 +29423,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28654,11 +29433,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28674,7 +29453,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28685,7 +29464,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28699,11 +29478,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28711,10 +29490,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28726,7 +29505,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28739,13 +29518,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28758,7 +29537,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28774,13 +29553,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28790,7 +29569,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28807,26 +29586,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28834,18 +29615,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28853,7 +29636,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28864,22 +29647,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28888,7 +29671,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28899,7 +29682,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28908,24 +29691,24 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 199 /* AwaitExpression */: @@ -28999,7 +29782,7 @@ var ts; case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: @@ -29046,8 +29829,8 @@ var ts; // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29056,58 +29839,58 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; case 150 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; @@ -29115,8 +29898,8 @@ var ts; break; case 185 /* ArrayLiteralExpression */: case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; @@ -29127,22 +29910,22 @@ var ts; case 223 /* ForStatement */: case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29164,27 +29947,27 @@ var ts; case 189 /* CallExpression */: case 190 /* NewExpression */: case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; + return 647001409 /* ModuleExcludes */; case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; + return 637535553 /* ParameterExcludes */; case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; + return 653604161 /* ArrowFunctionExcludes */; case 194 /* FunctionExpression */: case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; + return 653620545 /* FunctionExcludes */; case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; + return 639894849 /* VariableDeclarationListExcludes */; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; + return 638121281 /* ClassExcludes */; case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; + return 653616449 /* ConstructorExcludes */; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; + return 653616449 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: @@ -29203,12 +29986,12 @@ var ts; case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; + return 638358849 /* ObjectLiteralExcludes */; case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; + return 637797697 /* CatchClauseExcludes */; case 182 /* ObjectBindingPattern */: case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; + return 637666625 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: case 306 /* PartiallyEmittedExpression */: @@ -29217,9 +30000,9 @@ var ts; return 536872257 /* OuterExpressionExcludes */; case 187 /* PropertyAccessExpression */: case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29434,6 +30217,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30249,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29463,6 +30259,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -29670,8 +30467,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29739,7 +30536,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29769,8 +30567,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29804,6 +30615,7 @@ var ts; var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29815,6 +30627,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +30647,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +30659,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29933,6 +30747,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29975,6 +30791,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +30928,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,7 +30989,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30184,8 +31002,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30206,53 +31025,54 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30360,8 +31180,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30504,7 +31324,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30513,15 +31333,23 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 149 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173 /* ConditionalType */) { @@ -30599,7 +31427,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30609,7 +31437,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30636,7 +31467,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30656,7 +31487,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30730,7 +31561,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30739,7 +31570,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,14 +31625,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30897,9 +31728,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +31749,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30951,7 +31785,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30968,6 +31802,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31037,7 +31874,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +31928,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31147,7 +31984,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31181,7 +32018,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31200,7 +32037,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31215,10 +32052,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32086,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31298,11 +32135,11 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31311,11 +32148,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31331,7 +32168,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32203,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32219,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,6 +32241,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32277,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32296,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32328,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32336,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,24 +32348,23 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -31737,7 +32592,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31837,7 +32692,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +32742,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31952,11 +32810,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +32852,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32102,7 +32970,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32112,7 +32980,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32135,6 +33003,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32217,7 +33088,12 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -32262,13 +33138,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32288,7 +33164,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32355,17 +33231,20 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); @@ -32435,23 +33314,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32533,8 +33412,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +33452,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +33465,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32684,18 +33563,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32823,7 +33697,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +33708,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32875,6 +33749,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32884,12 +33761,22 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32996,7 +33883,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,7 +33898,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33103,6 +33997,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33161,7 +34058,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33345,10 +34242,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34266,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34315,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33426,6 +34325,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33590,27 +34491,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33618,11 +34519,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33670,7 +34571,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33701,16 +34602,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +34637,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33753,8 +34660,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +34669,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,7 +34679,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33783,15 +34690,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +34715,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +34729,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33851,9 +34756,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33876,8 +34779,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +34788,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33899,8 +34802,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33992,9 +34895,9 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -34037,19 +34940,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +34973,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34124,7 +35034,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34152,14 +35062,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34182,7 +35090,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34210,7 +35118,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35127,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35156,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35165,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34431,23 +35331,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34518,7 +35415,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -34529,8 +35428,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34629,7 +35528,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34768,9 +35667,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -34996,7 +35895,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +35915,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35270,7 +36169,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35407,7 +36306,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35430,7 +36329,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35484,6 +36383,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35595,7 +36495,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35765,10 +36665,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35785,7 +36690,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35864,6 +36770,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +36778,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35894,8 +36811,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35910,7 +36827,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35920,9 +36837,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,6 +36886,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35979,14 +36907,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36016,10 +36945,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36110,8 +37039,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -36192,7 +37125,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36292,7 +37225,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37238,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36342,7 +37275,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37306,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36460,7 +37393,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36501,6 +37434,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36537,7 +37471,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36556,8 +37490,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +37536,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36792,10 +37730,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36825,7 +37763,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36880,14 +37818,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +37847,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36904,16 +37856,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -37029,16 +37986,16 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37087,10 +38044,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37118,6 +38075,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37144,7 +38104,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37265,6 +38225,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37333,10 +38301,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38316,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37405,7 +38361,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37433,7 +38389,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37530,10 +38486,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +38495,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37797,7 +38750,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37810,20 +38763,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { @@ -37869,7 +38825,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37887,7 +38843,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37895,20 +38854,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37922,37 +38867,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +38905,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38000,17 +38933,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38188,7 +39132,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39162,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39176,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38374,8 +39318,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38385,7 +39329,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38591,7 +39535,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38692,7 +39636,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +39646,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38761,8 +39705,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +39726,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38819,6 +39777,12 @@ var ts; var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38858,49 +39822,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38974,7 +39954,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39022,8 +40002,9 @@ var ts; return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 131072 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39049,33 +40030,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40130,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40147,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39115,13 +40161,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40204,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40237,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39239,8 +40293,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,9 +40324,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39295,11 +40350,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39325,13 +40380,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39495,10 +40550,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39633,10 +40688,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39692,13 +40747,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39797,7 +40849,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39807,32 +40859,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39849,8 +40875,8 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39888,13 +40914,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +40952,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39950,32 +40980,24 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -40140,6 +41162,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40168,20 +41221,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40199,7 +41257,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40272,6 +41329,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40305,36 +41382,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +41424,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40491,33 +41558,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40549,8 +41589,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40742,6 +41782,52 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41030,8 +42116,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41083,9 +42169,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -41107,10 +42198,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41135,13 +42226,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41153,7 +42248,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41167,11 +42262,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41408,8 +42504,12 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { case 202 /* BinaryExpression */: @@ -41432,44 +42532,49 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41645,7 +42750,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41731,11 +42838,13 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -41784,6 +42893,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41819,7 +42931,22 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41915,33 +43042,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +43083,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ || kind === 155 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +43127,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42011,7 +43151,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +43169,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +43182,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +43195,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +43224,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +43253,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42238,14 +43409,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144 /* Union */) { + if (type.flags & (16 /* Boolean */ | 512 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 /* Unit */ && !(combined & 15794176 /* Instantiable */)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -42289,6 +43476,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42297,8 +43496,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +43512,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42344,13 +43550,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42390,7 +43598,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42476,10 +43684,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42525,6 +43733,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42549,6 +43774,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 /* Union */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144 /* Union */) { var types = type.types; @@ -42567,8 +43795,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42648,8 +43876,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42729,8 +43957,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42833,11 +44061,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,6 +44074,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42869,7 +44105,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42905,15 +44142,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43172,12 +44415,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43188,11 +44441,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43211,6 +44461,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43223,7 +44549,7 @@ var ts; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43240,22 +44566,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43379,8 +44695,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43388,7 +44704,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { if (node.kind === 71 /* Identifier */) { @@ -43436,7 +44752,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43480,8 +44796,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); @@ -43495,8 +44811,8 @@ var ts; while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43509,7 +44825,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43587,6 +44903,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || @@ -43611,22 +44930,42 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (container.kind === 223 /* ForStatement */ && ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; @@ -43768,31 +45107,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,13 +45144,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -43898,16 +45262,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43919,19 +45285,20 @@ var ts; // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; @@ -44039,7 +45406,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44096,7 +45463,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44163,9 +45530,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44212,7 +45591,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,13 +45612,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44249,9 +45635,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,19 +45655,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44299,6 +45712,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +45721,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44329,8 +45740,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44395,47 +45806,36 @@ var ts; case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 71 /* Identifier */: + case 140 /* UndefinedKeyword */: return true; case 187 /* PropertyAccessExpression */: case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 268 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44475,6 +45875,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); + case 199 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); case 189 /* CallExpression */: case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); @@ -44500,7 +45902,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44519,6 +45921,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44527,7 +45935,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44599,11 +46007,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44709,8 +46117,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44746,7 +46154,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +46176,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,7 +46185,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44789,35 +46197,47 @@ var ts; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44907,9 +46327,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44927,7 +46347,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45137,12 +46557,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45159,7 +46581,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +46589,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,7 +46598,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45191,14 +46613,16 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45215,7 +46639,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45248,7 +46672,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45296,7 +46720,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45306,7 +46730,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45373,7 +46797,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +46821,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45619,7 +47043,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45735,7 +47159,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45856,10 +47280,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45904,7 +47328,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46059,6 +47483,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46172,7 +47602,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46277,7 +47707,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46343,7 +47773,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46351,7 +47781,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46472,16 +47902,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46499,7 +47926,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46510,11 +47937,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46545,7 +47972,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,7 +47981,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46612,58 +48039,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46671,12 +48080,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,23 +48091,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46756,36 +48162,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46799,19 +48196,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46819,283 +48217,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 150 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,6 +48306,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47112,7 +48315,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,16 +48329,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47165,36 +48380,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47264,14 +48463,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +48493,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47364,7 +48586,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47375,7 +48597,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47414,17 +48636,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47477,11 +48709,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47493,16 +48725,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47575,11 +48814,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47649,10 +48890,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47676,8 +48918,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47716,8 +48958,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47745,7 +48987,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47824,34 +49066,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,14 +49110,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47924,7 +49167,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,7 +49178,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47945,8 +49188,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49215,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48031,7 +49274,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48156,14 +49399,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +49412,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,15 +49436,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48222,6 +49443,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48307,6 +49539,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48424,10 +49666,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48477,7 +49770,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48547,6 +49840,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48556,8 +49850,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48598,7 +49894,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48803,8 +50098,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48964,7 +50259,7 @@ var ts; if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48990,8 +50285,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49105,7 +50400,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49243,9 +50538,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49260,15 +50555,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49321,8 +50616,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +50626,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49437,7 +50732,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49479,19 +50774,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49522,11 +50813,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49573,15 +50864,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +50890,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +50907,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49633,13 +50932,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49664,7 +50963,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49757,9 +51056,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49789,7 +51085,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50255,7 +51551,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +51582,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50387,8 +51683,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50627,6 +51923,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,13 +51987,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50720,10 +52016,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50953,7 +52249,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50976,7 +52272,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51033,7 +52329,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51291,8 +52587,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51302,7 +52598,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51788,7 +53084,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51871,7 +53167,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51911,7 +53207,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51927,7 +53223,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52301,13 +53597,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52334,9 +53634,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52877,7 +54179,10 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -52888,7 +54193,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52931,7 +54236,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52950,7 +54255,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -53114,6 +54419,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53603,8 +54910,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53615,7 +54922,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53668,14 +54975,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53729,13 +55036,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53766,7 +55073,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +55105,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53846,7 +55153,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54013,7 +55320,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54084,13 +55391,20 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: @@ -54144,9 +55458,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54157,7 +55470,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54260,7 +55572,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54345,12 +55657,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54375,7 +55687,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54401,7 +55713,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54413,7 +55725,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54439,10 +55751,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54458,7 +55770,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54472,7 +55784,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54489,7 +55801,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54568,7 +55880,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54584,6 +55896,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54593,7 +55906,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,30 +55914,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54719,13 +56027,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54786,13 +56113,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54841,7 +56168,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,11 +56181,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54874,7 +56201,7 @@ var ts; // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -54950,7 +56277,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +56290,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +56335,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55052,9 +56398,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55156,7 +56502,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +56517,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +56573,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55266,7 +56616,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55280,9 +56635,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55371,6 +56726,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55415,6 +56773,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55442,31 +56802,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55478,7 +56837,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55852,11 +57211,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56034,6 +57414,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56077,8 +57460,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56295,6 +57680,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56391,26 +57779,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56550,10 +57944,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56584,8 +57979,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60161,6 +61556,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +61584,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -62811,8 +64209,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62878,7 +64276,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63818,7 +65216,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63866,9 +65264,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -65782,7 +67182,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65904,7 +67304,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -66044,6 +67444,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66077,6 +67485,16 @@ var ts; return visitFunctionExpression(node); case 195 /* ArrowFunction */: return visitArrowFunction(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66318,23 +67736,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66352,6 +67780,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66387,6 +67817,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -66409,6 +67841,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66437,13 +67877,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66468,18 +67908,62 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66507,12 +67991,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66535,6 +68019,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66603,6 +68093,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272 /* CatchClause */: return visitCatchClause(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66667,7 +68167,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -66699,7 +68199,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 26 /* CommaToken */) { @@ -66714,7 +68214,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66731,7 +68231,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66828,7 +68328,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66925,25 +68425,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66967,7 +68479,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -66996,6 +68508,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -67018,6 +68532,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67046,13 +68568,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67077,13 +68599,13 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67741,6 +69263,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67921,7 +69448,7 @@ var ts; return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -68519,7 +70046,7 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 /* BinaryExpression */ || superCallExpression.left.kind !== 189 /* CallExpression */) { @@ -68590,7 +70117,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68719,7 +70246,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68907,7 +70434,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69197,19 +70724,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69257,8 +70792,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69513,7 +71048,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -69544,7 +71079,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69570,7 +71121,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69586,7 +71137,69 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 225 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 221 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 222 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223 /* ForStatement */: @@ -69603,165 +71216,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.thisName; } else { // this is top level converted loop so we need to create an alias for 'this' here // NOTE: // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69769,24 +71493,24 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { @@ -69799,8 +71523,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69840,21 +71564,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69994,7 +71726,7 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156 /* GetAccessor */) { @@ -70173,7 +71905,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || node.expression.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -70181,7 +71913,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70228,7 +71960,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70710,7 +72442,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -71135,10 +72867,10 @@ var ts; case 228 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71341,7 +73073,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71465,10 +73197,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71729,10 +73461,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -72399,7 +74131,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72431,10 +74163,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -73516,7 +75248,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +75305,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +75336,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73849,7 +75587,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73916,7 +75654,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74881,7 +76619,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75966,7 +77704,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76773,7 +78511,7 @@ var ts; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -76808,11 +78546,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +78576,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +78594,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +78604,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76937,15 +78676,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,11 +78697,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -76974,6 +78715,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +78734,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +78747,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77038,7 +78784,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77046,13 +78792,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,6 +78813,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77578,10 +79338,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77804,7 +79579,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77818,7 +79593,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -77865,10 +79640,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -78870,7 +80646,7 @@ var ts; emitCallback(node); } if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + ts.performance.mark("beginEmitBodyWithDetachedComments"); } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); @@ -78879,7 +80655,7 @@ var ts; } } if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedComments"); } } function emitLeadingComments(pos, isEmittedNode) { @@ -79100,20 +80876,25 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79136,7 +80917,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79185,26 +80966,31 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -79229,12 +81015,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79963,7 +81749,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79985,7 +81771,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80410,7 +82196,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80621,7 +82407,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81324,13 +83112,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81356,11 +83144,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81525,7 +83318,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81946,19 +83740,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82137,7 +83931,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +84010,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82730,17 +84524,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +84557,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +84567,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +84575,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +84587,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +84599,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +84615,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +84649,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +84676,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +84764,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +84780,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83044,7 +84842,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +84851,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,8 +84875,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83084,21 +84902,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83149,7 +84963,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -83196,7 +85010,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83208,11 +85022,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83299,7 +85114,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +85150,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83378,13 +85195,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83469,8 +85286,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,15 +85298,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83516,15 +85329,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83532,16 +85350,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83564,7 +85381,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,7 +85408,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83657,7 +85478,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83673,7 +85494,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83708,14 +85530,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +85555,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +85570,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +85633,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +85699,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +85790,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84188,7 +86019,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84296,7 +86127,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84352,11 +86183,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84371,6 +86205,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84436,7 +86271,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -84457,6 +86292,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84486,24 +86322,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +86351,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84600,7 +86438,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +86447,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +86467,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,27 +86487,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84677,7 +86507,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84688,22 +86518,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84743,9 +86567,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84755,17 +86580,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +86639,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84850,7 +86674,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84863,9 +86687,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84880,15 +86704,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85079,7 +86903,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,7 +86920,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85104,17 +86931,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85184,7 +87008,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +87018,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +87047,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,11 +87058,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85752,7 +87616,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +87629,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +87810,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86097,7 +87968,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86235,7 +88106,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86575,121 +88447,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - 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]; + return count; } 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; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +88621,6 @@ var ts; result.push.apply(result, targets); return result; } - 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 = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +88638,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +88659,30 @@ var ts; 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 + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // 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); @@ -86827,20 +88691,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; 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)) { // TODO: GH#18217 - 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 (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86855,12 +88717,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86923,13 +88787,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +88855,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,7 +88863,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87031,7 +88913,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +88929,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87081,6 +88963,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + 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 args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +88994,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +89008,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - 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 args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87166,18 +89060,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,9 +89095,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87273,7 +89169,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87311,9 +89208,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +89235,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87519,12 +89416,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87550,7 +89442,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87637,6 +89531,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +89553,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +89571,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +89642,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +89657,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,808 +89678,820 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +90527,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +90539,142 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +90682,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88700,8 +90727,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88776,7 +90803,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +90888,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +90926,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +91017,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89104,6 +91066,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89319,8 +91305,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89377,7 +91364,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89499,6 +91486,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89629,7 +91623,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89993,7 +91987,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +92005,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +92014,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90250,7 +92242,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90364,7 +92356,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +92364,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90514,6 +92506,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); @@ -90883,7 +92882,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +92890,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -90906,14 +92905,14 @@ var ts; ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_7 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_7)) { - clone_7.textSourceNode = node; + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_7)) { - clone_7.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_7, node); + return ts.setTextRange(clone_8, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -91273,7 +93272,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +93281,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -92040,9 +94039,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_10(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92056,27 +94088,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -92085,15 +94105,15 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_11 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); } } if (!foundGlobal) { @@ -92202,7 +94222,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -92235,7 +94255,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -92259,6 +94279,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92366,11 +94398,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92386,7 +94419,7 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) @@ -92471,7 +94504,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +94512,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +94540,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92578,6 +94612,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92663,11 +94700,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92675,16 +94713,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92697,11 +94740,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92715,7 +94758,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92742,6 +94785,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -93150,7 +95198,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +95223,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +95232,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93317,7 +95370,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -93332,9 +95385,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,7 +95422,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93399,12 +95450,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93423,7 +95474,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93444,7 +95495,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93474,7 +95525,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93498,6 +95549,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93733,7 +95791,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93767,14 +95826,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 71 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93928,10 +95992,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93943,6 +96004,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93963,7 +96026,6 @@ var ts; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: case 75 /* ClassKeyword */: case 76 /* ConstKeyword */: case 124 /* DeclareKeyword */: @@ -93978,6 +96040,8 @@ var ts; case 104 /* VarKeyword */: case 116 /* YieldKeyword */: return true; + case 120 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -94151,17 +96215,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94184,7 +96250,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -94256,7 +96322,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94276,14 +96342,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94748,9 +96814,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94795,7 +96858,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +96872,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94876,6 +96939,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -95161,8 +97227,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -95192,8 +97258,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95312,7 +97378,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95457,8 +97523,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95490,9 +97573,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -95505,10 +97588,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95521,28 +97604,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95560,24 +97643,61 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: name + ": " }; + } + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95609,17 +97729,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95635,7 +97755,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95699,11 +97874,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95717,7 +97892,7 @@ var ts; break; case 242 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95725,7 +97900,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95763,7 +97938,7 @@ var ts; 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: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!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); @@ -95894,15 +98069,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -96005,19 +98180,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -96047,7 +98209,7 @@ var ts; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -96062,8 +98224,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -96112,8 +98274,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,7 +98332,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -96197,7 +98359,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96367,12 +98529,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96602,7 +98765,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96660,8 +98823,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96669,39 +98833,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96713,8 +98863,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96727,11 +98895,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96739,19 +98909,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96777,8 +98947,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +99010,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96943,9 +99113,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_12 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +99141,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_12(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +99171,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +99201,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +99243,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97332,6 +99509,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97542,7 +99729,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +99762,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +99825,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97698,7 +99885,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97741,7 +99928,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +99938,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +99953,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -98090,7 +100277,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98416,28 +100603,49 @@ var ts; return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { @@ -99248,13 +101456,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_14 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_14(start); if (typeof state_3 === "object") return state_3.value; } @@ -99794,9 +102002,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; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99805,28 +102013,42 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); @@ -99877,22 +102099,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +102133,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99928,12 +102164,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +102186,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -100238,8 +102474,8 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100248,8 +102484,8 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +102500,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +102517,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100336,7 +102592,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100460,13 +102716,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100489,7 +102745,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100533,13 +102789,13 @@ var ts; switch (statement.kind) { case 217 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); case 219 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100564,10 +102820,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100577,7 +102833,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100596,22 +102852,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100744,13 +103023,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100888,7 +103170,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -101118,7 +103400,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101190,7 +103472,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -101257,6 +103540,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +103614,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_16 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +103633,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_16(opt); } return options; } @@ -102982,13 +105266,13 @@ var ts; var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } @@ -104156,11 +106440,11 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -104175,7 +106459,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -104190,11 +106482,33 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertCommentThenNewline = function (sourceFile, character, position, commentText) { + var token = ts.getTouchingToken(sourceFile, position); + var text = "/**" + commentText + "*/" + this.newLineCharacter + ts.repeatString(" ", character); + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + ChangeTracker.prototype.tryInsertJSDocParameters = function (sourceFile, parameters) { + if (parameters.length === 0) { + return; + } + var parent = parameters[0].declaration.parent; + var indent = ts.getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; + var commentText = "\n"; + for (var _i = 0, parameters_3 = parameters; _i < parameters_3.length; _i++) { + var _a = parameters_3[_i], declaration = _a.declaration, typeNode = _a.typeNode, isOptional = _a.isOptional; + if (ts.isIdentifier(declaration.name)) { + var printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; + commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); + } + } + commentText += ts.repeatString(" ", indent + 1); + this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -104213,6 +106527,25 @@ var ts; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; + ChangeTracker.prototype.tryInsertJSDocType = function (sourceFile, node, type) { + var printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; + var commentText; + if (ts.isGetAccessorDeclaration(node)) { + commentText = " @return {" + printed + "} "; + } + else { + commentText = " @type {" + printed + "} "; + node = node.parent; + } + this.insertCommentThenNewline(sourceFile, ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); + }; + ChangeTracker.prototype.printJSDocParameter = function (indent, printed, name, isOptionalParameter) { + var printName = ts.unescapeLeadingUnderscores(name.escapedText); + if (isOptionalParameter) { + printName = "[" + printName + "]"; + } + return ts.repeatString(" ", indent) + (" * @param {" + printed + "} " + printName + "\n"); + }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); @@ -104256,30 +106589,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +106642,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104427,7 +106767,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104459,7 +106799,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +106807,29 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var _loop_17 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +106842,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_17(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +106881,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +106899,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +106916,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes); + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,9 +106965,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -105399,7 +107751,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105452,57 +107804,63 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_19(statement); } } // Returns the identifiers that are never reassigned in the refactor @@ -105549,7 +107907,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +107921,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +107935,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +107961,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +107984,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +107994,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,7 +108028,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105670,17 +108044,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +108071,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +108087,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,50 +108100,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105774,49 +108168,66 @@ var ts; refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105837,12 +108248,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +108255,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105941,7 +108344,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -106058,7 +108461,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106544,33 +108947,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); 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, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106631,24 +109041,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, 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; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106690,7 +109100,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106738,17 +109148,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +109164,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +109187,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -107009,10 +109430,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107051,7 +109472,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +109501,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_20 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +109528,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_20(info); } }); })); @@ -107151,7 +109572,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,7 +109582,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -107281,7 +109702,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +109714,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -108045,7 +110578,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108177,22 +110710,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -108202,7 +110732,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108300,38 +110830,35 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */ && token.kind !== 99 /* ThisKeyword */) { return undefined; } var parent = token.parent; @@ -108340,14 +110867,22 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + changes.tryInsertJSDocType(sourceFile, parent, typeNode); + } return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -108360,30 +110895,30 @@ var ts; switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); return param; } return undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -108391,9 +110926,9 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } function isApplicableFunctionForInference(declaration) { @@ -108407,36 +110942,62 @@ var ts; } return false; } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, host, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 151 /* PropertySignature */) { + changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var result = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + return typeNode && !param.initializer && !ts.getJSDocType(param) ? __assign({}, inference, { typeNode: typeNode }) : undefined; + }); + changes.tryInsertJSDocParameters(sourceFile, result); + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); var typeIsAccessible = true; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -108447,13 +111008,21 @@ var ts; reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; }); } function inferTypeForVariableFromUsage(token, program, cancellationToken) { @@ -108504,9 +111073,11 @@ var ts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; var isRest = ts.isRestParameter(parameter); + var isOptional = false; for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); continue; } if (isRest) { @@ -108519,10 +111090,14 @@ var ts; } } if (!types.length) { - return undefined; + return { declaration: parameter }; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -108750,16 +111325,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_6.set(name, symbol); }); } @@ -108775,17 +111352,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -109005,7 +111582,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109031,6 +111608,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109481,7 +112258,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_21 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +112277,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_21(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -110126,7 +112903,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110342,7 +113119,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110676,7 +113453,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +113509,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_22 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +113549,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_22(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -111046,7 +113823,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111178,7 +113955,7 @@ var ts; return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; @@ -111322,10 +114099,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_23 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_24 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,12 +114124,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_24(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_23(sourceFile); } } function getNamespaceLikeImport(node) { @@ -111770,7 +114547,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112344,8 +115121,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112523,7 +115300,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112865,8 +115642,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +115681,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112924,7 +115706,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -113039,7 +115821,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +115864,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113162,27 +115944,25 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113389,19 +116169,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -115398,15 +118190,16 @@ var ts; function isNonDuplicateInSortedArray(value, index, array) { return index === 0 || value !== array[index - 1]; } + var indentStr = "\n "; /* @internal */ function indent(str) { - return "\n " + str; + return indentStr + str.replace(/\n/g, indentStr); } server.indent = indent; /** Put stringified JSON on the next line, indented. */ /* @internal */ function stringifyIndented(json) { - return "\n " + JSON.stringify(json); + return indentStr + JSON.stringify(json); } server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); @@ -115715,7 +118508,7 @@ var ts; var fileName = tempFileName || this.fileName; var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; // Only non typescript files have size limitation - if (!ts.hasTypeScriptFileExtension(this.fileName)) { + if (!ts.hasTSFileExtension(this.fileName)) { var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > server.maxFileSize) { ts.Debug.assert(!!this.info.containingProjects.length); @@ -116030,6 +118823,7 @@ var ts; isKnownTypesPackageName: ts.returnFalse, // Should never be called because we never provide a types registry. installPackage: ts.notImplemented, + inspectValue: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -116091,6 +118885,9 @@ var ts; TypingsCache.prototype.installPackage = function (options) { return this.installer.installPackage(options); }; + TypingsCache.prototype.inspectValue = function (options) { + return this.installer.inspectValue(options); + }; TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -116236,6 +119033,7 @@ var ts; * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project */ this.projectStateVersion = 0; + this.isInitialLoadPending = ts.returnFalse; /*@internal*/ this.dirty = false; /*@internal*/ @@ -116301,6 +119099,10 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + /* @internal */ + Project.prototype.inspectValue = function (options) { + return this.typingsCache.inspectValue(options); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -116385,6 +119187,9 @@ var ts; Project.prototype.readFile = function (fileName) { return this.projectService.host.readFile(fileName); }; + Project.prototype.writeFile = function (fileName, content) { + return this.projectService.host.writeFile(fileName, content); + }; Project.prototype.fileExists = function (file) { // As an optimization, don't hit the disks for files we already know don't exist // (because we're watching for their creation). @@ -116568,7 +119373,7 @@ var ts; var f = _a[_i]; this.detachScriptInfoIfNotRoot(f.fileName); } - var projectReferences = this.program.getProjectReferences(); + var projectReferences = this.program.getResolvedProjectReferences(); if (projectReferences) { for (var _b = 0, projectReferences_2 = projectReferences; _b < projectReferences_2.length; _b++) { var ref = projectReferences_2[_b]; @@ -116639,7 +119444,7 @@ var ts; return this.rootFiles; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { - var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; }); return scriptInfo; }); @@ -116949,8 +119754,8 @@ var ts; var sourceFiles = this.program.getSourceFiles(); var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; if (writeProjectFileNames) { - for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { - var file = sourceFiles_9[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var file = sourceFiles_7[_i]; strBuilder += "\t" + file.fileName + "\n"; } } @@ -116973,7 +119778,10 @@ var ts; }; /* @internal */ Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - server.updateProjectIfDirty(this); + // Update the graph only if initial configured project load is not pending + if (!this.isInitialLoadPending()) { + server.updateProjectIfDirty(this); + } var info = { projectName: this.getProjectName(), version: this.projectProgramVersion, @@ -117026,9 +119834,8 @@ var ts; ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); }; - Project.prototype.enableGlobalPlugins = function () { + Project.prototype.enableGlobalPlugins = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117037,7 +119844,7 @@ var ts; // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_26 = function (globalPluginName) { + var _loop_25 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -117052,7 +119859,7 @@ var ts; // Enable global plugins with synthetic configuration entries for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_26(globalPluginName); + _loop_25(globalPluginName); } } }; @@ -117127,7 +119934,7 @@ var ts; if (!projectRootPath && !projectService.useSingleInferredProject) { _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory); } - _this.enableGlobalPlugins(); + _this.enableGlobalPlugins(_this.getCompilerOptions()); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -117210,14 +120017,18 @@ var ts; var ConfiguredProject = /** @class */ (function (_super) { __extends(ConfiguredProject, _super); /*@internal*/ - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { - var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; - _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectReferences = projectReferences; + function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, + /*hasExplicitListOfFiles*/ false, + /*lastFileExceededProgramSize*/ undefined, + /*compilerOptions*/ {}, + /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; /** Ref count to the project when opened from external project */ _this.externalProjectRefCount = 0; + _this.isInitialLoadPending = ts.returnTrue; + /*@internal*/ + _this.sendLoadingProjectFinish = false; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); - _this.enablePlugins(); return _this; } /** @@ -117225,17 +120036,27 @@ var ts; * @returns: true if set of files in the project stays the same and false - otherwise. */ ConfiguredProject.prototype.updateGraph = function () { + this.isInitialLoadPending = ts.returnFalse; var reloadLevel = this.pendingReload; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + var result; switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: - return this.projectService.reloadFileNamesOfConfiguredProject(this); + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; case ts.ConfigFileProgramReloadLevel.Full: - this.projectService.reloadConfiguredProject(this); - return true; + var reason = ts.Debug.assertDefined(this.pendingReloadReason); + this.pendingReloadReason = undefined; + this.projectService.reloadConfiguredProject(this, reason); + result = true; + break; default: - return _super.prototype.updateGraph.call(this); + result = _super.prototype.updateGraph.call(this); } + this.projectService.sendProjectLoadingFinishEvent(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; }; /*@internal*/ ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { @@ -117253,11 +120074,14 @@ var ts; /*@internal*/ ConfiguredProject.prototype.getResolvedProjectReferences = function () { var program = this.getCurrentProgram(); - return program && program.getProjectReferences(); + return program && program.getResolvedProjectReferences(); }; ConfiguredProject.prototype.enablePlugins = function () { + this.enablePluginsWithOptions(this.getCompilerOptions()); + }; + /*@internal*/ + ConfiguredProject.prototype.enablePluginsWithOptions = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117277,7 +120101,7 @@ var ts; this.enablePlugin(pluginConfigEntry, searchPaths); } } - this.enableGlobalPlugins(); + this.enableGlobalPlugins(options); }; /** * Get the errors that dont have any file name associated @@ -117355,17 +120179,16 @@ var ts; // The project is referenced only if open files impacted by this project are present in this project return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; + /*@internal*/ + ConfiguredProject.prototype.hasExternalProjectRef = function () { + return !!this.externalProjectRefCount; + }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; }; /*@internal*/ - ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (hasFileNames) { - if (hasFileNames) { - ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); // TODO: GH#18217 - } - else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { // TODO: GH#18217 - this.projectErrors.push(ts.getErrorForNoInputFiles(this.configFileSpecs, this.getConfigFilePath())); - } + ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) { + ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); }; return ConfiguredProject; }(Project)); @@ -117385,6 +120208,12 @@ var ts; _this.excludedFiles = []; return _this; } + ExternalProject.prototype.updateGraph = function () { + var result = _super.prototype.updateGraph.call(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; @@ -117412,6 +120241,9 @@ var ts; server.maxFileSize = 4 * 1024 * 1024; // tslint:disable variable-name server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.ProjectLoadingStartEvent = "projectLoadingStart"; + server.ProjectLoadingFinishEvent = "projectLoadingFinish"; + server.SurveyReady = "surveyReady"; server.LargeFileReferencedEvent = "largeFileReferenced"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -117522,6 +120354,12 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; + /*@internal*/ + function convertUserPreferences(preferences) { + var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]); + return userPreferences; + } + server.convertUserPreferences = convertUserPreferences; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -117565,6 +120403,7 @@ var ts; WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; WatchType["TypeRoots"] = "Type root directory"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; })(WatchType = server.WatchType || (server.WatchType = {})); var ConfigFileWatcherStatus; (function (ConfigFileWatcherStatus) { @@ -117582,11 +120421,19 @@ var ts; function getDetailWatchInfo(watchType, project) { return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== undefined; + } /*@internal*/ function updateProjectIfDirty(project) { return project.dirty && project.updateGraph(); } server.updateProjectIfDirty = updateProjectIfDirty; + function setProjectOptionsUsed(project) { + if (project.projectKind === server.ProjectKind.Configured) { + project.projectOptions = true; + } + } var ProjectService = /** @class */ (function () { function ProjectService(opts) { var _this = this; @@ -117594,6 +120441,7 @@ var ts; * Container of all known scripts */ this.filenameToScriptInfo = ts.createMap(); + this.scriptInfoInNodeModulesWatchers = ts.createMap(); /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -117640,10 +120488,12 @@ var ts; */ this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist = ts.createMap(); this.pendingProjectUpdates = ts.createMap(); /** Tracks projects that we have already sent telemetry for. */ this.seenProjects = ts.createMap(); + /** Tracks projects that we have already sent survey events for. */ + this.seenSurveyProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -117656,7 +120506,7 @@ var ts; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; this.syntaxOnly = opts.syntaxOnly; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); if (this.host.realpath) { @@ -117745,14 +120595,14 @@ var ts; this.safelist = raw.typesMap; for (var key in raw.simpleMap) { if (raw.simpleMap.hasOwnProperty(key)) { - this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); } } } catch (e) { this.logger.info("Error loading types map: " + e); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist.clear(); } }; ProjectService.prototype.updateTypingsForProject = function (response) { @@ -117819,6 +120669,13 @@ var ts; this.eventHandler(event); }; /* @internal */ + ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } }); + }; + /* @internal */ ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { if (!this.eventHandler) { return; @@ -117830,6 +120687,30 @@ var ts; this.eventHandler(event); }; /* @internal */ + ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + var event = { + eventName: server.ProjectLoadingStartEvent, + data: { project: project, reason: reason } + }; + this.eventHandler(event); + }; + /* @internal */ + ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + project.sendLoadingProjectFinish = false; + var event = { + eventName: server.ProjectLoadingFinishEvent, + data: { project: project } + }; + this.eventHandler(event); + }; + /* @internal */ ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) { this.delayUpdateProjectGraph(project); this.delayEnsureProjectForOpenFiles(); @@ -118027,6 +120908,7 @@ var ts; else { this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */); project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = "Change in config file detected"; this.delayUpdateProjectGraph(project); // As we scheduled the update on configured project graph, // we would need to schedule the project reload for only the root of inferred projects @@ -118086,7 +120968,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_27 = function (inferredProject) { + var _loop_26 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -118107,7 +120989,7 @@ var ts; // Note that we need to create a copy of the array since the list of project can change for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_27(inferredProject); + _loop_26(inferredProject); } } return project; @@ -118482,35 +121364,6 @@ var ts; ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { return findProjectByName(projectFileName, this.externalProjects); }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { - configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 - var result = ts.parseJsonText(configFilename, configFileContent); - if (!result.endOfFileToken) { - result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; - } - var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), - /*existingOptions*/ {}, configFilename, - /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); - if (parsedCommandLine.errors.length) { - errors.push.apply(errors, parsedCommandLine.errors); - } - ts.Debug.assert(!!parsedCommandLine.fileNames); - var projectOptions = { - files: parsedCommandLine.fileNames, - compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, - configHasFilesProperty: parsedCommandLine.raw.files !== undefined, - configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, - configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, - wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), - typeAcquisition: parsedCommandLine.typeAcquisition, - compileOnSave: parsedCommandLine.compileOnSave, - projectReferences: parsedCommandLine.projectReferences - }; - return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; - }; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { @@ -118523,12 +121376,12 @@ var ts; for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var f = fileNames_2[_i]; var fileName = propertyReader.getFileName(f); - if (ts.hasTypeScriptFileExtension(fileName)) { + if (ts.hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // Keep the size as zero since it's disabled return fileName; } @@ -118540,9 +121393,9 @@ var ts; return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); } function getTop5LargestFiles(_a) { - var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; + var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .filter(function (name) { return hasTypeScriptFileExtension(name); }) + .filter(function (name) { return hasTSFileExtension(name); }) .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217 .sort(function (a, b) { return b.size - a.size; }) .slice(0, 5); @@ -118553,21 +121406,37 @@ var ts; var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); project.excludedFiles = excludedFiles; - this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); - this.sendProjectTelemetry(projectFileName, project); return project; }; - ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { - if (this.seenProjects.has(projectKey)) { + /*@internal*/ + ProjectService.prototype.sendSurveyReady = function (project) { + if (this.seenSurveyProjects.has(project.projectName)) { return; } - this.seenProjects.set(projectKey, true); + if (project.getCompilerOptions().checkJs !== undefined) { + var name = "checkJs"; + this.logger.info("Survey " + name + " is ready"); + this.sendSurveyReadyEvent(name); + this.seenSurveyProjects.set(project.projectName, true); + } + }; + /*@internal*/ + ProjectService.prototype.sendProjectTelemetry = function (project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); + return; + } + this.seenProjects.set(project.projectName, true); if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); return; } + var projectOptions = project.projectKind === server.ProjectKind.Configured ? project.projectOptions : undefined; + setProjectOptionsUsed(project); var data = { - projectId: this.host.createSHA256Hash(projectKey), + projectId: this.host.createSHA256Hash(project.projectName), fileStats: server.countEachFileTypes(project.getScriptInfos()), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), @@ -118586,8 +121455,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; // TODO: GH#18217 - return server.getBaseConfigFileName(configFilePath) || "other"; + return server.getBaseConfigFileName(project.getConfigFilePath()) || "other"; } function convertTypeAcquisition(_a) { var enable = _a.enable, include = _a.include, exclude = _a.exclude; @@ -118598,34 +121466,88 @@ var ts; }; } }; - ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { + ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) { this.updateNonInferredProjectFiles(project, files, propertyReader); project.setTypeAcquisition(typeAcquisition); - // This doesnt need scheduling since its either creation or reload of the project - project.updateGraph(); }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217 - var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, // TODO: GH#18217 - lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); - project.configFileSpecs = configFileSpecs; + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); // TODO: We probably should also watch the configFiles that are extended project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project); - if (!lastFileExceededProgramSize) { - project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 - } - project.setProjectErrors(configFileErrors); - var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); // TODO: GH#18217 this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); - this.sendProjectTelemetry(configFileName, project, projectOptions); return project; }; + /* @internal */ + ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; + return project; + }; + /* @internal */ + ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project, reason); + return project; + }; + /* @internal */ + ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) { + var project = this.createAndLoadConfiguredProject(configFileName, reason); + project.updateGraph(); + return project; + }; + /** + * Read the config file of the project, and update the project root file names. + */ + /* @internal */ + ProjectService.prototype.loadConfiguredProject = function (project, reason) { + this.sendProjectLoadingStartEvent(project, reason); + // Read updated contents from disk + var configFilename = ts.normalizePath(project.getConfigFilePath()); + var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; + } + var configFileErrors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), + /*existingOptions*/ {}, configFilename, + /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + var compilerOptions = parsedCommandLine.options; + // Update the project + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + }; + } + project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(parsedCommandLine.raw); + project.setProjectErrors(configFileErrors); + project.updateReferences(parsedCommandLine.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + project.stopWatchingWildCards(); + } + else { + project.enableLanguageService(); + project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); // TODO: GH#18217 + } + project.enablePluginsWithOptions(compilerOptions); + var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); // TODO: GH#18217 + }; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = ts.createMap(); @@ -118681,14 +121603,14 @@ var ts; // mark the project as dirty unconditionally project.markAsDirty(); }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { + ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently // therefore if it is undefined, it should not be updated. if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } - this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; /** * Reload the file names from config file specs and update the project graph @@ -118698,37 +121620,24 @@ var ts; var configFileSpecs = project.configFileSpecs; // TODO: GH#18217 var configFileName = project.getConfigFilePath(); var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); - project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); - this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); + project.updateErrorOnNoInputFiles(fileNamesResult); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); }; /** - * Read the config file of the project again and update the project + * Read the config file of the project again by clearing the cache and update the project graph */ /* @internal */ - ProjectService.prototype.reloadConfiguredProject = function (project) { + ProjectService.prototype.reloadConfiguredProject = function (project, reason) { // At this point, there is no reason to not have configFile in the host var host = project.getCachedDirectoryStructureHost(); // Clear the cache since we are reloading the project from disk host.clearCache(); var configFileName = project.getConfigFilePath(); this.logger.info("Reloading configured project " + configFileName); - // Read updated contents from disk - var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; - // Update the project - project.configFileSpecs = configFileSpecs; - project.setProjectErrors(configFileErrors); - project.updateReferences(projectOptions.projectReferences); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 - if (lastFileExceededProgramSize) { - project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - } - else { - project.enableLanguageService(); - project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 - } - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); // TODO: GH#18217 + // Load project from the disk + this.loadConfiguredProject(project, reason); + project.updateGraph(); this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { @@ -118853,7 +121762,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_28 = function (project) { + var _loop_27 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && @@ -118870,7 +121779,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_28(project); + _loop_27(project); } } } @@ -118883,10 +121792,80 @@ var ts; if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - var fileName = info.fileName; - info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); + var indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } } }; + ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) { + var _this = this; + // Watch only directory + var existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + var watchDir = dir + "/node_modules"; + var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + // Has extension + ts.Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + _this.refreshScriptInfosInDirectory(watchDir); + } + else { + var info = _this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + _this.refreshScriptInfo(info); + } + } + // Folder + else if (!ts.hasExtension(fileOrDirectoryPath)) { + _this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, 1 /* Recursive */, "node_modules for closed script infos in them" /* NodeModulesForClosedScriptInfo */); + var result = { + close: function () { + if (result.refCount === 1) { + watcher.close(); + _this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + }; + ProjectService.prototype.getModifiedTime = function (info) { + return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime(); + }; + ProjectService.prototype.refreshScriptInfo = function (info) { + var mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + }; + ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) { + var _this = this; + dir = dir + ts.directorySeparator; + this.filenameToScriptInfo.forEach(function (info) { + if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) { + _this.refreshScriptInfo(info); + } + }); + }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { if (info.fileWatcher) { info.fileWatcher.close(); @@ -118952,6 +121931,7 @@ var ts; return this.filenameToScriptInfo.get(fileName); }; ProjectService.prototype.setHostConfiguration = function (args) { + var _this = this; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { @@ -118969,7 +121949,18 @@ var ts; this.logger.info("Format host information updated"); } if (args.preferences) { + var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject; this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences); + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + // Load configured projects for external projects that are pending reload + this.configuredProjects.forEach(function (project) { + if (project.hasExternalProjectRef() && + project.pendingReload === ts.ConfigFileProgramReloadLevel.Full && + !_this.pendingProjectUpdates.has(project.getProjectName())) { + project.updateGraph(); + } + }); + } } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; @@ -118994,7 +121985,7 @@ var ts; // (and would separate out below reloading of projects to be called when immediate reload is needed) // as there is no need to load contents of the files from the disk // Reload Projects - this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue); + this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue, "User requested reload projects"); this.ensureProjectForOpenFiles(); }; ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { @@ -119002,8 +121993,8 @@ var ts; this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, /*delayReload*/ true, ignoreIfNotRootOfInferredProject ? function (isRootOfInferredProject) { return isRootOfInferredProject; } : // Reload open files if they are root of inferred project - ts.returnTrue // Reload all the open files impacted by config file - ); + ts.returnTrue, // Reload all the open files impacted by config file + "Change in config file detected"); this.delayEnsureProjectForOpenFiles(); }; /** @@ -119013,7 +122004,7 @@ var ts; * If the there is no existing project it just opens the configured project for the config file * reloadForInfo provides a way to filter out files to reload configured project for */ - ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor) { + ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) { var _this = this; var updatedProjects = ts.createMap(); // try to reload config file for all open files @@ -119030,18 +122021,16 @@ var ts; // otherwise we create a new one. var configFileName = _this.getConfigFileNameForFile(info); if (configFileName) { - var project = _this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - _this.createConfiguredProject(configFileName); - updatedProjects.set(configFileName, true); - } - else if (!updatedProjects.has(configFileName)) { + var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName); + if (!updatedProjects.has(configFileName)) { if (delayReload) { project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; _this.delayUpdateProjectGraph(project); } else { - _this.reloadConfiguredProject(project); + // reload from the disk + _this.reloadConfiguredProject(project, reason); } updatedProjects.set(configFileName, true); } @@ -119121,7 +122110,8 @@ var ts; var configFileName = this.getConfigFileNameForFile(originalFileInfo); if (!configFileName) return undefined; - var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || + this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName); updateProjectIfDirty(configuredProject); // Keep this configured project as referenced from project addOriginalConfiguredProject(configuredProject); @@ -119165,7 +122155,7 @@ var ts; if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createConfiguredProject(configFileName); + project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open"); // Send the event only if the project got created as part of this open request and info is part of the project if (info.isOrphan()) { // Since the file isnt part of configured project, do not send config file info @@ -119276,13 +122266,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_29 = function (proj) { + var _loop_28 = function (proj) { var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_29(proj); + _loop_28(proj); } }; /* @internal */ @@ -119392,7 +122382,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_30 = function (name) { + var _loop_29 = function (name) { var rule = this_3.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -119410,7 +122400,7 @@ var ts; } } if (rule.exclude) { - var _loop_32 = function (exclude) { + var _loop_31 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -119437,7 +122427,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_32(exclude); + _loop_31(exclude); } } else { @@ -119453,11 +122443,11 @@ var ts; var this_3 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_30(name); + _loop_29(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_31 = function (i) { + var _loop_30 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -119468,13 +122458,13 @@ var ts; if (ts.fileExtensionIs(baseName, "js")) { var inferredTypingName = ts.removeFileExtension(baseName); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - if (this_4.legacySafelist[cleanedTypingName]) { + var typeName = this_4.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { this_4.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); excludedFiles.push(normalizedNames[i]); // *exclude* it from the project... exclude = true; // ... but *include* it in the list of types to acquire - var typeName = this_4.legacySafelist[cleanedTypingName]; // Same best-effort dedupe as above if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); @@ -119495,7 +122485,7 @@ var ts; }; var this_4 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_31(i); + _loop_30(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -119546,7 +122536,9 @@ var ts; externalProject.enableLanguageService(); } // external project already exists and not config files were added - update the project and return; - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + // The graph update here isnt postponed since any file open operation needs all updated external projects + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + externalProject.updateGraph(); return; } // some config files were added to external project (that previously were not there) @@ -119594,8 +122586,10 @@ var ts; var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { - // errors are stored in the project - project = this.createConfiguredProject(tsconfigFile); + // errors are stored in the project, do not need to update the graph + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? + this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project @@ -119605,8 +122599,11 @@ var ts; } else { // no config files - remove the item from the collection + // Create external project and update its graph, do not delay update since + // any file open operation needs all updated external projects this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); } }; ProjectService.prototype.hasDeferredExtension = function () { @@ -119822,7 +122819,7 @@ var ts; /** * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. */ - function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { + function combineProjectOutput(defaultValue, getValue, projects, action) { var outputs = ts.flatMap(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); if (!ts.isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach(function (projects, path) { @@ -119830,9 +122827,7 @@ var ts; outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); }); } - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); + return ts.deduplicate(outputs, ts.equateValues); } function combineProjectOutputFromEveryProject(projectService, action, areEqual) { var outputs = []; @@ -119877,24 +122872,27 @@ var ts; } function combineProjectOutputForReferences(projects, defaultProject, initialLocation, projectService) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, getMappedLocation) { var project = _a.project, location = _a.location; - var _loop_33 = function (outputReferencedSymbol) { - var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, outputReferencedSymbol.definition); }); + var _loop_32 = function (outputReferencedSymbol) { + var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.position, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); if (!symbolToAddTo) { - symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + symbolToAddTo = { definition: definition, references: [] }; outputs.push(symbolToAddTo); } for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { var ref = _a[_i]; - if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { symbolToAddTo.references.push(ref); } } }; for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.position) || server.emptyArray; _i < _b.length; _i++) { var outputReferencedSymbol = _b[_i]; - _loop_33(outputReferencedSymbol); + _loop_32(outputReferencedSymbol); } }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); return outputs.filter(function (o) { return o.references.length !== 0; }); @@ -119950,7 +122948,7 @@ var ts; seenProjects.set(projectAndLocation.project.projectName, true); var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); if (!originalLocation) - return false; + return undefined; var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); toDo = toDo || []; for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { @@ -119966,7 +122964,7 @@ var ts; } }); } - return true; + return originalLocation; }); return toDo; } @@ -120326,6 +123324,7 @@ var ts; globalPlugins: opts.globalPlugins, pluginProbeLocations: opts.pluginProbeLocations, allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, syntaxOnly: opts.syntaxOnly, }; this.projectService = new server.ProjectService(settings); @@ -120340,21 +123339,33 @@ var ts; var openFiles = event.data.openFiles; this.projectsUpdatedInBackgroundEvent(openFiles); break; + case server.ProjectLoadingStartEvent: + var _a = event.data, project = _a.project, reason = _a.reason; + this.event({ projectName: project.getProjectName(), reason: reason }, server.ProjectLoadingStartEvent); + break; + case server.ProjectLoadingFinishEvent: + var finishProject = event.data.project; + this.event({ projectName: finishProject.getProjectName() }, server.ProjectLoadingStartEvent); + break; case server.LargeFileReferencedEvent: - var _a = event.data, file = _a.file, fileSize = _a.fileSize, maxFileSize_1 = _a.maxFileSize; - this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, "largeFileReferenced"); + var _b = event.data, file = _b.file, fileSize = _b.fileSize, maxFileSize_1 = _b.maxFileSize; + this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, server.LargeFileReferencedEvent); break; case server.ConfigFileDiagEvent: - var _b = event.data, triggerFile = _b.triggerFile, configFile = _b.configFileName, diagnostics = _b.diagnostics; + var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics; var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ true); }); this.event({ triggerFile: triggerFile, configFile: configFile, diagnostics: bakedDiags - }, "configFileDiag"); + }, server.ConfigFileDiagEvent); + break; + case server.SurveyReady: + var surveyId = event.data.surveyId; + this.event({ surveyId: surveyId }, server.SurveyReady); break; case server.ProjectLanguageServiceStateEvent: { - var eventName = "projectLanguageServiceState"; + var eventName = server.ProjectLanguageServiceStateEvent; this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled @@ -120383,10 +123394,13 @@ var ts; // Send project changed event this.event({ openFiles: openFiles - }, "projectsUpdatedInBackground"); + }, server.ProjectsUpdatedInBackgroundEvent); } }; Session.prototype.logError = function (err, cmd) { + this.logErrorWorker(err, cmd); + }; + Session.prototype.logErrorWorker = function (err, cmd, fileRequest) { var msg = "Exception on executing command " + cmd; if (err.message) { msg += ":\n" + server.indent(err.message); @@ -120394,6 +123408,17 @@ var ts; msg += "\n" + server.indent(err.stack); } } + if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) { + try { + var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + var text = ts.getSnapshotText(scriptInfo.getSnapshot()); + msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + } + } + catch (_b) { } // tslint:disable-line no-empty + } this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { @@ -120852,22 +123877,28 @@ var ts; if (!simplifiedResult) return locations; var defaultProject = this.getDefaultProject(args); - var renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; - // strips 'triggerSpan' - Session.mapRenameInfo = function (_a) { - var canRename = _a.canRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers; - return { canRename: canRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers }; + Session.prototype.mapRenameInfo = function (info, scriptInfo) { + if (info.canRename) { + var canRename = info.canRename, fileToRename = info.fileToRename, displayName = info.displayName, fullDisplayName = info.fullDisplayName, kind = info.kind, kindModifiers = info.kindModifiers, triggerSpan = info.triggerSpan; + return ts.identity({ canRename: canRename, fileToRename: fileToRename, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }); + } + else { + return info; + } }; Session.prototype.toSpanGroups = function (locations) { var map = ts.createMap(); for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { - var _a = locations_1[_i], fileName = _a.fileName, textSpan = _a.textSpan; + var _a = locations_1[_i]; + var fileName = _a.fileName, textSpan = _a.textSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "originalTextSpan", "originalFileName"]); var group_2 = map.get(fileName); if (!group_2) map.set(fileName, group_2 = { file: fileName, locs: [] }); - group_2.locs.push(this.toLocationTextSpan(textSpan, ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)))); + var scriptInfo = ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)); + group_2.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText)); } return ts.arrayFrom(map.values()); }; @@ -120884,7 +123915,7 @@ var ts; var symbolDisplayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : ""; var nameSpan = nameInfo && nameInfo.textSpan; var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; - var symbolName_4 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; + var symbolName_3 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; var refs = ts.flatMap(references, function (referencedSymbol) { return referencedSymbol.references.map(function (_a) { var fileName = _a.fileName, textSpan = _a.textSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition; @@ -120895,7 +123926,7 @@ var ts; return __assign({}, toFileSpan(fileName, textSpan, scriptInfo), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition }); }); }); - var result = { refs: refs, symbolName: symbolName_4, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; + var result = { refs: refs, symbolName: symbolName_3, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; return result; } else { @@ -121099,7 +124130,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); if (completions === undefined) return undefined; if (kind === "completions-full" /* CompletionsFull */) @@ -121441,8 +124472,8 @@ var ts; var commands = args.command; // They should be sending back the command we sent them. for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; - var project = this.getFileAndProject(command).project; - project.getLanguageService().applyCodeActionCommand(command).then(function (_result) { }, function (_error) { }); + var _b = this.getFileAndProject(command), file = _b.file, project = _b.project; + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { }); } return {}; }; @@ -121602,8 +124633,10 @@ var ts; } } var request; + var relevantFile; try { request = JSON.parse(message); + relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; if (this.logger.hasLevel(server.LogLevel.requestTime)) { var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); @@ -121627,7 +124660,7 @@ var ts; this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); return; } - this.logError(err, message); + this.logErrorWorker(err, message, relevantFile); this.doOutput( /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); @@ -121686,8 +124719,8 @@ var ts; continue; } for (var i = textChanges_4.length - 1; i >= 0; i--) { - var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_7 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_7); + var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_6 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_6); } } return text; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 096362cc6a7..fdd11aa3484 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ const version: string; } @@ -69,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -536,6 +537,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +634,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +671,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -1079,7 +1083,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1808,7 +1812,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -2056,32 +2061,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2490,6 +2495,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2587,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2597,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2698,9 +2695,6 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -3001,6 +2995,16 @@ declare namespace ts { Parameters = 1296, IndexSignatureParameters = 4432 } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3209,17 +3213,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -4171,14 +4185,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4318,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4361,14 +4387,6 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; } /** * Host to create watch with root files and options @@ -4378,6 +4396,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4432,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,184 +4443,11 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4609,7 +4456,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4817,14 +4664,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4882,9 +4722,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5046,9 +4886,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5114,6 +4961,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5266,15 +5115,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; diff --git a/lib/typescript.js b/lib/typescript.js index 78365f95075..bb0d451215a 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -62,7 +62,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -73,7 +73,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -88,6 +88,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -716,17 +717,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -771,7 +778,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1148,7 +1155,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1275,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1432,7 +1443,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1935,6 +1948,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2029,6 +2046,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2615,6 +2992,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2665,6 +3043,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2734,38 +3114,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2840,14 +3220,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2993,9 +3374,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3394,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3266,25 +3646,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3303,25 +3679,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3565,20 +3940,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3796,17 +4157,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4127,11 +4492,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4742,7 +5108,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5147,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5024,7 +5394,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5421,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5520,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5634,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5730,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5828,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5867,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5545,6 +5934,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5673,10 +6063,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { return token >= 71 /* Identifier */; @@ -5687,136 +6080,85 @@ var ts; return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 117 /* AbstractKeyword */, + any: 119 /* AnyKeyword */, + as: 118 /* AsKeyword */, + boolean: 122 /* BooleanKeyword */, + break: 72 /* BreakKeyword */, + case: 73 /* CaseKeyword */, + catch: 74 /* CatchKeyword */, + class: 75 /* ClassKeyword */, + continue: 77 /* ContinueKeyword */, + const: 76 /* ConstKeyword */ + }, + _a["" + "constructor"] = 123 /* ConstructorKeyword */, + _a.debugger = 78 /* DebuggerKeyword */, + _a.declare = 124 /* DeclareKeyword */, + _a.default = 79 /* DefaultKeyword */, + _a.delete = 80 /* DeleteKeyword */, + _a.do = 81 /* DoKeyword */, + _a.else = 82 /* ElseKeyword */, + _a.enum = 83 /* EnumKeyword */, + _a.export = 84 /* ExportKeyword */, + _a.extends = 85 /* ExtendsKeyword */, + _a.false = 86 /* FalseKeyword */, + _a.finally = 87 /* FinallyKeyword */, + _a.for = 88 /* ForKeyword */, + _a.from = 143 /* FromKeyword */, + _a.function = 89 /* FunctionKeyword */, + _a.get = 125 /* GetKeyword */, + _a.if = 90 /* IfKeyword */, + _a.implements = 108 /* ImplementsKeyword */, + _a.import = 91 /* ImportKeyword */, + _a.in = 92 /* InKeyword */, + _a.infer = 126 /* InferKeyword */, + _a.instanceof = 93 /* InstanceOfKeyword */, + _a.interface = 109 /* InterfaceKeyword */, + _a.is = 127 /* IsKeyword */, + _a.keyof = 128 /* KeyOfKeyword */, + _a.let = 110 /* LetKeyword */, + _a.module = 129 /* ModuleKeyword */, + _a.namespace = 130 /* NamespaceKeyword */, + _a.never = 131 /* NeverKeyword */, + _a.new = 94 /* NewKeyword */, + _a.null = 95 /* NullKeyword */, + _a.number = 134 /* NumberKeyword */, + _a.object = 135 /* ObjectKeyword */, + _a.package = 111 /* PackageKeyword */, + _a.private = 112 /* PrivateKeyword */, + _a.protected = 113 /* ProtectedKeyword */, + _a.public = 114 /* PublicKeyword */, + _a.readonly = 132 /* ReadonlyKeyword */, + _a.require = 133 /* RequireKeyword */, + _a.global = 144 /* GlobalKeyword */, + _a.return = 96 /* ReturnKeyword */, + _a.set = 136 /* SetKeyword */, + _a.static = 115 /* StaticKeyword */, + _a.string = 137 /* StringKeyword */, + _a.super = 97 /* SuperKeyword */, + _a.switch = 98 /* SwitchKeyword */, + _a.symbol = 138 /* SymbolKeyword */, + _a.this = 99 /* ThisKeyword */, + _a.throw = 100 /* ThrowKeyword */, + _a.true = 101 /* TrueKeyword */, + _a.try = 102 /* TryKeyword */, + _a.type = 139 /* TypeKeyword */, + _a.typeof = 103 /* TypeOfKeyword */, + _a.undefined = 140 /* UndefinedKeyword */, + _a.unique = 141 /* UniqueKeyword */, + _a.unknown = 142 /* UnknownKeyword */, + _a.var = 104 /* VarKeyword */, + _a.void = 105 /* VoidKeyword */, + _a.while = 106 /* WhileKeyword */, + _a.with = 107 /* WithKeyword */, + _a.yield = 116 /* YieldKeyword */, + _a.async = 120 /* AsyncKeyword */, + _a.await = 121 /* AwaitKeyword */, + _a.of = 145 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, ">": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -6394,6 +6736,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6423,6 +6766,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6820,9 +7164,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -6878,6 +7222,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7261,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6973,6 +7336,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7478,7 +7846,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7555,6 +7923,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +7946,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7657,22 +8027,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8134,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8001,12 +8364,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,13 +8404,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8408,6 +8779,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8468,6 +8843,7 @@ var ts; case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: case 138 /* SymbolKeyword */: + case 135 /* ObjectKeyword */: case 140 /* UndefinedKeyword */: case 131 /* NeverKeyword */: return true; @@ -9135,18 +9511,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9186,14 +9562,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9216,15 +9592,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9232,26 +9612,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,7 +9640,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9274,30 +9654,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9308,7 +9688,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9352,12 +9732,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9367,9 +9747,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9398,7 +9778,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,11 +9787,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9517,7 +9897,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9559,6 +9939,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9749,6 +10133,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9773,32 +10163,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9857,7 +10251,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10260,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10600,7 +10994,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10614,7 +11008,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10735,7 +11129,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11145,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11035,13 +11429,18 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -11063,15 +11462,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } @@ -11107,10 +11497,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11249,6 +11639,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +11751,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11514,6 +11928,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11525,12 +11941,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11756,13 +12194,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12090,13 +12521,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12108,9 +12539,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12118,10 +12547,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12152,7 +12579,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12198,15 +12625,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12653,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12353,7 +12796,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13699,7 +14155,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14092,6 +14548,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14576,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14589,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14401,8 +14869,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15090,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14684,6 +15157,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14910,36 +15384,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15067,14 +15562,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +15740,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -15333,6 +15844,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15403,6 +15915,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15761,7 +16274,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16443,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -16599,7 +17116,15 @@ var ts; // which would be a candidate for improved error reporting. return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 21 /* OpenBracketToken */: + case 39 /* AsteriskToken */: + case 24 /* DotDotDotToken */: + case 23 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: @@ -17367,8 +17892,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19464,8 +19991,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -20866,7 +21394,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -20991,13 +21519,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21012,7 +21533,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21083,7 +21606,7 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -21264,10 +21787,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21281,14 +21802,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21376,7 +21897,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21391,7 +21912,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21452,7 +21973,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21492,17 +22013,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21530,7 +22051,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21556,9 +22077,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -22399,8 +22918,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +22932,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22461,21 +23015,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22490,6 +23029,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23049,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23062,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23070,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23088,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23198,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23207,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23216,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23242,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23251,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23285,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23298,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23306,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23316,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23332,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23344,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23355,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22874,30 +23440,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23504,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23524,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23570,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23578,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23606,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23634,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +23725,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +23775,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +23795,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +23803,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +23839,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +23882,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +23907,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23619,7 +24249,11 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -23926,7 +24560,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24578,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23980,19 +24629,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +24648,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +24661,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24110,11 +24773,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24161,7 +24819,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +24827,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25041,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24408,10 +25066,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24421,9 +25084,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24431,7 +25110,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24442,16 +25121,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24640,6 +25319,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24656,7 +25341,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25350,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24750,7 +25481,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24770,7 +25502,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24797,11 +25528,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,7 +25548,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24856,14 +25594,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -25086,15 +25828,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +25874,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +25893,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,74 +25904,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25241,8 +25969,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25250,7 +25978,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +25992,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +26009,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,7 +26040,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25352,52 +26081,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25411,12 +26134,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26153,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26191,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,51 +26203,56 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25550,87 +26272,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26402,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,43 +26415,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25695,24 +26460,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26492,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25944,13 +26709,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -25995,7 +26764,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26075,7 +26844,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26153,12 +26923,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26321,6 +27091,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -26419,6 +27190,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -26821,7 +27594,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -27217,7 +27989,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +28009,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27325,9 +28097,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27347,7 +28116,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27572,7 +28341,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27619,7 +28388,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27636,15 +28405,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27717,15 +28486,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27741,7 +28510,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27752,9 +28521,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27835,37 +28604,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27901,7 +28668,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27931,7 +28698,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -27988,7 +28755,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28009,7 +28776,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28035,40 +28802,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,7 +28843,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28090,7 +28856,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28174,8 +28940,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,10 +28956,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28207,7 +28976,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +28994,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,10 +29035,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28278,14 +29047,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28304,9 +29073,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,7 +29111,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(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; })); } @@ -28382,6 +29149,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28457,40 +29227,40 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28511,7 +29281,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28522,25 +29292,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28575,35 +29345,35 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28621,7 +29391,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28632,7 +29402,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28644,7 +29414,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28654,11 +29424,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28674,7 +29444,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28685,7 +29455,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28699,11 +29469,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28711,10 +29481,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28726,7 +29496,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28739,13 +29509,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28758,7 +29528,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28774,13 +29544,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28790,7 +29560,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28807,26 +29577,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28834,18 +29606,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28853,7 +29627,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28864,22 +29638,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28888,7 +29662,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28899,7 +29673,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28908,24 +29682,24 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 199 /* AwaitExpression */: @@ -28999,7 +29773,7 @@ var ts; case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: @@ -29046,8 +29820,8 @@ var ts; // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29056,58 +29830,58 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; case 150 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; @@ -29115,8 +29889,8 @@ var ts; break; case 185 /* ArrayLiteralExpression */: case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; @@ -29127,22 +29901,22 @@ var ts; case 223 /* ForStatement */: case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29164,27 +29938,27 @@ var ts; case 189 /* CallExpression */: case 190 /* NewExpression */: case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; + return 647001409 /* ModuleExcludes */; case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; + return 637535553 /* ParameterExcludes */; case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; + return 653604161 /* ArrowFunctionExcludes */; case 194 /* FunctionExpression */: case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; + return 653620545 /* FunctionExcludes */; case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; + return 639894849 /* VariableDeclarationListExcludes */; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; + return 638121281 /* ClassExcludes */; case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; + return 653616449 /* ConstructorExcludes */; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; + return 653616449 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: @@ -29203,12 +29977,12 @@ var ts; case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; + return 638358849 /* ObjectLiteralExcludes */; case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; + return 637797697 /* CatchClauseExcludes */; case 182 /* ObjectBindingPattern */: case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; + return 637666625 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: case 306 /* PartiallyEmittedExpression */: @@ -29217,9 +29991,9 @@ var ts; return 536872257 /* OuterExpressionExcludes */; case 187 /* PropertyAccessExpression */: case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29434,6 +30208,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30240,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29463,6 +30250,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -29670,8 +30458,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29739,7 +30527,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29769,8 +30558,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29804,6 +30606,7 @@ var ts; var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29815,6 +30618,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +30638,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +30650,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29933,6 +30738,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29975,6 +30782,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +30919,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,7 +30980,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30184,8 +30993,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30206,53 +31016,54 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30360,8 +31171,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30504,7 +31315,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30513,15 +31324,23 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 149 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173 /* ConditionalType */) { @@ -30599,7 +31418,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30609,7 +31428,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30636,7 +31458,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30656,7 +31478,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30730,7 +31552,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30739,7 +31561,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,14 +31616,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30897,9 +31719,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +31740,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30951,7 +31776,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30968,6 +31793,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31037,7 +31865,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +31919,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31147,7 +31975,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31181,7 +32009,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31200,7 +32028,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31215,10 +32043,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32077,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31298,11 +32126,11 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31311,11 +32139,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31331,7 +32159,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32194,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32210,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,6 +32232,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32268,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32287,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32319,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32327,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,24 +32339,23 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -31737,7 +32583,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31837,7 +32683,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +32733,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31952,11 +32801,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +32843,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32102,7 +32961,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32112,7 +32971,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32135,6 +32994,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32217,7 +33079,12 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -32262,13 +33129,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32288,7 +33155,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32355,17 +33222,20 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); @@ -32435,23 +33305,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32533,8 +33403,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +33443,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +33456,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32684,18 +33554,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32823,7 +33688,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +33699,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32875,6 +33740,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32884,12 +33752,22 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32996,7 +33874,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,7 +33889,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33103,6 +33988,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33161,7 +34049,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33345,10 +34233,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34257,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34306,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33426,6 +34316,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33590,27 +34482,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33618,11 +34510,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33670,7 +34562,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33701,16 +34593,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +34628,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33753,8 +34651,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +34660,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,7 +34670,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33783,15 +34681,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +34706,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +34720,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33851,9 +34747,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33876,8 +34770,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +34779,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33899,8 +34793,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33992,9 +34886,9 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -34037,19 +34931,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +34964,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34124,7 +35025,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34152,14 +35053,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34182,7 +35081,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34210,7 +35109,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35118,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35147,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35156,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34431,23 +35322,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34518,7 +35406,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -34529,8 +35419,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34629,7 +35519,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34768,9 +35658,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -34996,7 +35886,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +35906,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35270,7 +36160,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35407,7 +36297,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35430,7 +36320,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35484,6 +36374,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35595,7 +36486,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35765,10 +36656,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35785,7 +36681,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35864,6 +36761,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +36769,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35894,8 +36802,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35910,7 +36818,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35920,9 +36828,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,6 +36877,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35979,14 +36898,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36016,10 +36936,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36110,8 +37030,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -36192,7 +37116,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36292,7 +37216,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37229,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36342,7 +37266,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37297,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36460,7 +37384,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36501,6 +37425,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36537,7 +37462,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36556,8 +37481,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +37527,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36792,10 +37721,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36825,7 +37754,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36880,14 +37809,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +37838,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36904,16 +37847,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -37029,16 +37977,16 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37087,10 +38035,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37118,6 +38066,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37144,7 +38095,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37265,6 +38216,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37333,10 +38292,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38307,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37405,7 +38352,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37433,7 +38380,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37530,10 +38477,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +38486,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37797,7 +38741,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37810,20 +38754,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { @@ -37869,7 +38816,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37887,7 +38834,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37895,20 +38845,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37922,37 +38858,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +38896,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38000,17 +38924,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38188,7 +39123,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39153,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39167,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38374,8 +39309,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38385,7 +39320,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38591,7 +39526,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38692,7 +39627,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +39637,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38761,8 +39696,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +39717,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38819,6 +39768,12 @@ var ts; var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38858,49 +39813,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38974,7 +39945,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39022,8 +39993,9 @@ var ts; return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 131072 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39049,33 +40021,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40121,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40138,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39115,13 +40152,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40195,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40228,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39239,8 +40284,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,9 +40315,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39295,11 +40341,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39325,13 +40371,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39495,10 +40541,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39633,10 +40679,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39692,13 +40738,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39797,7 +40840,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39807,32 +40850,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39849,8 +40866,8 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39888,13 +40905,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +40943,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39950,32 +40971,24 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -40140,6 +41153,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40168,20 +41212,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40199,7 +41248,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40272,6 +41320,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40305,36 +41373,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +41415,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40491,33 +41549,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40549,8 +41580,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40742,6 +41773,52 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41030,8 +42107,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41083,9 +42160,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -41107,10 +42189,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41135,13 +42217,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41153,7 +42239,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41167,11 +42253,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41408,8 +42495,12 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { case 202 /* BinaryExpression */: @@ -41432,44 +42523,49 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41645,7 +42741,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41731,11 +42829,13 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -41784,6 +42884,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41819,7 +42922,22 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41915,33 +43033,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +43074,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ || kind === 155 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +43118,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42011,7 +43142,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +43160,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +43173,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +43186,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +43215,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +43244,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42238,14 +43400,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144 /* Union */) { + if (type.flags & (16 /* Boolean */ | 512 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 /* Unit */ && !(combined & 15794176 /* Instantiable */)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -42289,6 +43467,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42297,8 +43487,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +43503,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42344,13 +43541,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42390,7 +43589,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42476,10 +43675,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42525,6 +43724,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42549,6 +43765,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 /* Union */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144 /* Union */) { var types = type.types; @@ -42567,8 +43786,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42648,8 +43867,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42729,8 +43948,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42833,11 +44052,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,6 +44065,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42869,7 +44096,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42905,15 +44133,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43172,12 +44406,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43188,11 +44432,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43211,6 +44452,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43223,7 +44540,7 @@ var ts; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43240,22 +44557,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43379,8 +44686,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43388,7 +44695,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { if (node.kind === 71 /* Identifier */) { @@ -43436,7 +44743,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43480,8 +44787,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); @@ -43495,8 +44802,8 @@ var ts; while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43509,7 +44816,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43587,6 +44894,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || @@ -43611,22 +44921,42 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (container.kind === 223 /* ForStatement */ && ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; @@ -43768,31 +45098,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,13 +45135,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -43898,16 +45253,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43919,19 +45276,20 @@ var ts; // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; @@ -44039,7 +45397,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44096,7 +45454,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44163,9 +45521,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44212,7 +45582,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,13 +45603,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44249,9 +45626,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,19 +45646,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44299,6 +45703,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +45712,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44329,8 +45731,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44395,47 +45797,36 @@ var ts; case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 71 /* Identifier */: + case 140 /* UndefinedKeyword */: return true; case 187 /* PropertyAccessExpression */: case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 268 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44475,6 +45866,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); + case 199 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); case 189 /* CallExpression */: case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); @@ -44500,7 +45893,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44519,6 +45912,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44527,7 +45926,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44599,11 +45998,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44709,8 +46108,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44746,7 +46145,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +46167,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,7 +46176,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44789,35 +46188,47 @@ var ts; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44907,9 +46318,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44927,7 +46338,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45137,12 +46548,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45159,7 +46572,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +46580,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,7 +46589,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45191,14 +46604,16 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45215,7 +46630,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45248,7 +46663,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45296,7 +46711,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45306,7 +46721,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45373,7 +46788,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +46812,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45619,7 +47034,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45735,7 +47150,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45856,10 +47271,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45904,7 +47319,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46059,6 +47474,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46172,7 +47593,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46277,7 +47698,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46343,7 +47764,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46351,7 +47772,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46472,16 +47893,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46499,7 +47917,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46510,11 +47928,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46545,7 +47963,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,7 +47972,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46612,58 +48030,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46671,12 +48071,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,23 +48082,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46756,36 +48153,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46799,19 +48187,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46819,283 +48208,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 150 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,6 +48297,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47112,7 +48306,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,16 +48320,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47165,36 +48371,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47264,14 +48454,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +48484,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47364,7 +48577,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47375,7 +48588,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47414,17 +48627,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47477,11 +48700,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47493,16 +48716,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47575,11 +48805,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47649,10 +48881,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47676,8 +48909,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47716,8 +48949,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47745,7 +48978,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47824,34 +49057,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,14 +49101,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47924,7 +49158,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,7 +49169,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47945,8 +49179,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49206,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48031,7 +49265,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48156,14 +49390,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +49403,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,15 +49427,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48222,6 +49434,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48307,6 +49530,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48424,10 +49657,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48477,7 +49761,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48547,6 +49831,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48556,8 +49841,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48598,7 +49885,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48803,8 +50089,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48964,7 +50250,7 @@ var ts; if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48990,8 +50276,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49105,7 +50391,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49243,9 +50529,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49260,15 +50546,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49321,8 +50607,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +50617,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49437,7 +50723,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49479,19 +50765,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49522,11 +50804,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49573,15 +50855,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +50881,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +50898,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49633,13 +50923,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49664,7 +50954,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49757,9 +51047,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49789,7 +51076,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50255,7 +51542,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +51573,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50387,8 +51674,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50627,6 +51914,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,13 +51978,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50720,10 +52007,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50953,7 +52240,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50976,7 +52263,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51033,7 +52320,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51291,8 +52578,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51302,7 +52589,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51788,7 +53075,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51871,7 +53158,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51911,7 +53198,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51927,7 +53214,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52301,13 +53588,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52334,9 +53625,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52877,7 +54170,10 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -52888,7 +54184,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52931,7 +54227,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52950,7 +54246,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -53114,6 +54410,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53603,8 +54901,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53615,7 +54913,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53668,14 +54966,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53729,13 +55027,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53766,7 +55064,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +55096,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53846,7 +55144,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54013,7 +55311,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54084,13 +55382,20 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: @@ -54144,9 +55449,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54157,7 +55461,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54260,7 +55563,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54345,12 +55648,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54375,7 +55678,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54401,7 +55704,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54413,7 +55716,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54439,10 +55742,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54458,7 +55761,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54472,7 +55775,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54489,7 +55792,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54568,7 +55871,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54584,6 +55887,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54593,7 +55897,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,30 +55905,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54719,13 +56018,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54786,13 +56104,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54841,7 +56159,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,11 +56172,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54874,7 +56192,7 @@ var ts; // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -54950,7 +56268,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +56281,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +56326,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55052,9 +56389,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55156,7 +56493,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +56508,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +56564,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55266,7 +56607,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55280,9 +56626,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55371,6 +56717,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55415,6 +56764,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55442,31 +56793,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55478,7 +56828,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55852,11 +57202,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56034,6 +57405,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56077,8 +57451,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56295,6 +57671,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56391,26 +57770,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56550,10 +57935,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56584,8 +57970,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60161,6 +61547,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +61575,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -62811,8 +64200,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62878,7 +64267,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63818,7 +65207,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63866,9 +65255,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -65782,7 +67173,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65904,7 +67295,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -66044,6 +67435,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66077,6 +67476,16 @@ var ts; return visitFunctionExpression(node); case 195 /* ArrowFunction */: return visitArrowFunction(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66318,23 +67727,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66352,6 +67771,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66387,6 +67808,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -66409,6 +67832,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66437,13 +67868,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66468,18 +67899,62 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66507,12 +67982,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66535,6 +68010,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66603,6 +68084,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272 /* CatchClause */: return visitCatchClause(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66667,7 +68158,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -66699,7 +68190,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 26 /* CommaToken */) { @@ -66714,7 +68205,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66731,7 +68222,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66828,7 +68319,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66925,25 +68416,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66967,7 +68470,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -66996,6 +68499,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -67018,6 +68523,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67046,13 +68559,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67077,13 +68590,13 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67741,6 +69254,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67921,7 +69439,7 @@ var ts; return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -68519,7 +70037,7 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 /* BinaryExpression */ || superCallExpression.left.kind !== 189 /* CallExpression */) { @@ -68590,7 +70108,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68719,7 +70237,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68907,7 +70425,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69197,19 +70715,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69257,8 +70783,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69513,7 +71039,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -69544,7 +71070,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69570,7 +71112,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69586,7 +71128,69 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 225 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 221 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 222 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223 /* ForStatement */: @@ -69603,165 +71207,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.thisName; } else { // this is top level converted loop so we need to create an alias for 'this' here // NOTE: // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69769,24 +71484,24 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { @@ -69799,8 +71514,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69840,21 +71555,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69994,7 +71717,7 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156 /* GetAccessor */) { @@ -70173,7 +71896,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || node.expression.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -70181,7 +71904,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70228,7 +71951,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70710,7 +72433,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -71135,10 +72858,10 @@ var ts; case 228 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71341,7 +73064,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71465,10 +73188,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71729,10 +73452,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -72399,7 +74122,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72431,10 +74154,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -73516,7 +75239,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +75296,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +75327,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73849,7 +75578,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73916,7 +75645,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74881,7 +76610,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75966,7 +77695,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76773,7 +78502,7 @@ var ts; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -76808,11 +78537,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +78567,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +78585,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +78595,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76937,15 +78667,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,11 +78688,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -76974,6 +78706,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +78725,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +78738,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77038,7 +78775,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77046,13 +78783,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,6 +78804,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77578,10 +79329,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77804,7 +79570,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77818,7 +79584,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -77865,10 +79631,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -78870,7 +80637,7 @@ var ts; emitCallback(node); } if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + ts.performance.mark("beginEmitBodyWithDetachedComments"); } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); @@ -78879,7 +80646,7 @@ var ts; } } if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedComments"); } } function emitLeadingComments(pos, isEmittedNode) { @@ -79100,20 +80867,25 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79136,7 +80908,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79185,26 +80957,31 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -79229,12 +81006,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79963,7 +81740,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79985,7 +81762,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80410,7 +82187,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80621,7 +82398,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81324,13 +83103,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81356,11 +83135,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81525,7 +83309,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81946,19 +83731,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82137,7 +83922,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +84001,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82730,17 +84515,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +84548,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +84558,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +84566,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +84578,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +84590,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +84606,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +84640,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +84667,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +84755,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +84771,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83044,7 +84833,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +84842,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,8 +84866,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83084,21 +84893,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83149,7 +84954,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -83196,7 +85001,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83208,11 +85013,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83299,7 +85105,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +85141,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83378,13 +85186,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83469,8 +85277,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,15 +85289,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83516,15 +85320,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83532,16 +85341,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83564,7 +85372,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,7 +85399,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83657,7 +85469,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83673,7 +85485,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83708,14 +85521,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +85546,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +85561,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +85624,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +85690,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +85781,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84188,7 +86010,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84296,7 +86118,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84352,11 +86174,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84371,6 +86196,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84436,7 +86262,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -84457,6 +86283,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84486,24 +86313,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +86342,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84600,7 +86429,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +86438,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +86458,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,27 +86478,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84677,7 +86498,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84688,22 +86509,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84743,9 +86558,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84755,17 +86571,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +86630,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84850,7 +86665,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84863,9 +86678,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84880,15 +86695,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85079,7 +86894,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,7 +86911,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85104,17 +86922,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85184,7 +86999,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +87009,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +87038,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,11 +87049,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85752,7 +87607,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +87620,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +87801,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86097,7 +87959,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86235,7 +88097,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86575,121 +88438,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - 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]; + return count; } 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; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +88612,6 @@ var ts; result.push.apply(result, targets); return result; } - 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 = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +88629,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +88650,30 @@ var ts; 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 + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // 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); @@ -86827,20 +88682,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; 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)) { // TODO: GH#18217 - 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 (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86855,12 +88708,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86923,13 +88778,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +88846,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,7 +88854,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87031,7 +88904,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +88920,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87081,6 +88954,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + 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 args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +88985,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +88999,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - 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 args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87166,18 +89051,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,9 +89086,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87273,7 +89160,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87311,9 +89199,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +89226,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87519,12 +89407,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87550,7 +89433,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87637,6 +89522,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +89544,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +89562,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +89633,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +89648,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,808 +89669,820 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +90518,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +90530,142 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +90673,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88700,8 +90718,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88776,7 +90794,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +90879,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +90917,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +91008,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89104,6 +91057,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89319,8 +91296,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89377,7 +91355,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89499,6 +91477,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89629,7 +91614,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89993,7 +91978,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +91996,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +92005,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90250,7 +92233,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90364,7 +92347,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +92355,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90514,6 +92497,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); @@ -90883,7 +92873,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +92881,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -90906,14 +92896,14 @@ var ts; ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_7 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_7)) { - clone_7.textSourceNode = node; + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_7)) { - clone_7.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_7, node); + return ts.setTextRange(clone_8, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -91273,7 +93263,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +93272,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -92040,9 +94030,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_10(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92056,27 +94079,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -92085,15 +94096,15 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_11 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); } } if (!foundGlobal) { @@ -92202,7 +94213,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -92235,7 +94246,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -92259,6 +94270,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92366,11 +94389,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92386,7 +94410,7 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) @@ -92471,7 +94495,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +94503,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +94531,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92578,6 +94603,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92663,11 +94691,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92675,16 +94704,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92697,11 +94731,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92715,7 +94749,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92742,6 +94776,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -93150,7 +95189,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +95214,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +95223,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93317,7 +95361,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -93332,9 +95376,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,7 +95413,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93399,12 +95441,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93423,7 +95465,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93444,7 +95486,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93474,7 +95516,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93498,6 +95540,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93733,7 +95782,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93767,14 +95817,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 71 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93928,10 +95983,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93943,6 +95995,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93963,7 +96017,6 @@ var ts; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: case 75 /* ClassKeyword */: case 76 /* ConstKeyword */: case 124 /* DeclareKeyword */: @@ -93978,6 +96031,8 @@ var ts; case 104 /* VarKeyword */: case 116 /* YieldKeyword */: return true; + case 120 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -94151,17 +96206,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94184,7 +96241,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -94256,7 +96313,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94276,14 +96333,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94748,9 +96805,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94795,7 +96849,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +96863,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94876,6 +96930,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -95161,8 +97218,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -95192,8 +97249,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95312,7 +97369,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95457,8 +97514,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95490,9 +97564,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -95505,10 +97579,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95521,28 +97595,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95560,24 +97634,61 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: name + ": " }; + } + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95609,17 +97720,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95635,7 +97746,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95699,11 +97865,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95717,7 +97883,7 @@ var ts; break; case 242 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95725,7 +97891,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95763,7 +97929,7 @@ var ts; 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: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!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); @@ -95894,15 +98060,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -96005,19 +98171,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -96047,7 +98200,7 @@ var ts; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -96062,8 +98215,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -96112,8 +98265,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,7 +98323,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -96197,7 +98350,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96367,12 +98520,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96602,7 +98756,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96660,8 +98814,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96669,39 +98824,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96713,8 +98854,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96727,11 +98886,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96739,19 +98900,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96777,8 +98938,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +99001,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96943,9 +99104,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_12 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +99132,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_12(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +99162,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +99192,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +99234,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97332,6 +99500,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97542,7 +99720,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +99753,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +99816,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97698,7 +99876,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97741,7 +99919,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +99929,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +99944,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -98090,7 +100268,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98416,28 +100594,49 @@ var ts; return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { @@ -99248,13 +101447,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_14 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_14(start); if (typeof state_3 === "object") return state_3.value; } @@ -99794,9 +101993,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; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99805,28 +102004,42 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); @@ -99877,22 +102090,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +102124,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99928,12 +102155,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +102177,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -100238,8 +102465,8 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100248,8 +102475,8 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +102491,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +102508,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100336,7 +102583,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100460,13 +102707,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100489,7 +102736,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100533,13 +102780,13 @@ var ts; switch (statement.kind) { case 217 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); case 219 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100564,10 +102811,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100577,7 +102824,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100596,22 +102843,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100744,13 +103014,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100888,7 +103161,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -101118,7 +103391,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101190,7 +103463,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -101257,6 +103531,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +103605,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_16 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +103624,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_16(opt); } return options; } @@ -102982,13 +105257,13 @@ var ts; var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } @@ -104156,11 +106431,11 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -104175,7 +106450,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -104190,11 +106473,33 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertCommentThenNewline = function (sourceFile, character, position, commentText) { + var token = ts.getTouchingToken(sourceFile, position); + var text = "/**" + commentText + "*/" + this.newLineCharacter + ts.repeatString(" ", character); + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + ChangeTracker.prototype.tryInsertJSDocParameters = function (sourceFile, parameters) { + if (parameters.length === 0) { + return; + } + var parent = parameters[0].declaration.parent; + var indent = ts.getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; + var commentText = "\n"; + for (var _i = 0, parameters_3 = parameters; _i < parameters_3.length; _i++) { + var _a = parameters_3[_i], declaration = _a.declaration, typeNode = _a.typeNode, isOptional = _a.isOptional; + if (ts.isIdentifier(declaration.name)) { + var printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; + commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); + } + } + commentText += ts.repeatString(" ", indent + 1); + this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -104213,6 +106518,25 @@ var ts; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; + ChangeTracker.prototype.tryInsertJSDocType = function (sourceFile, node, type) { + var printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; + var commentText; + if (ts.isGetAccessorDeclaration(node)) { + commentText = " @return {" + printed + "} "; + } + else { + commentText = " @type {" + printed + "} "; + node = node.parent; + } + this.insertCommentThenNewline(sourceFile, ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); + }; + ChangeTracker.prototype.printJSDocParameter = function (indent, printed, name, isOptionalParameter) { + var printName = ts.unescapeLeadingUnderscores(name.escapedText); + if (isOptionalParameter) { + printName = "[" + printName + "]"; + } + return ts.repeatString(" ", indent) + (" * @param {" + printed + "} " + printName + "\n"); + }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); @@ -104256,30 +106580,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +106633,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104427,7 +106758,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104459,7 +106790,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +106798,29 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var _loop_17 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +106833,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_17(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +106872,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +106890,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +106907,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes); + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,9 +106956,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -105399,7 +107742,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105452,57 +107795,63 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_19(statement); } } // Returns the identifiers that are never reassigned in the refactor @@ -105549,7 +107898,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +107912,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +107926,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +107952,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +107975,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +107985,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,7 +108019,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105670,17 +108035,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +108062,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +108078,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,50 +108091,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105774,49 +108159,66 @@ var ts; refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105837,12 +108239,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +108246,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105941,7 +108335,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -106058,7 +108452,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106544,33 +108938,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); 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, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106631,24 +109032,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, 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; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106690,7 +109091,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106738,17 +109139,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +109155,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +109178,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -107009,10 +109421,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107051,7 +109463,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +109492,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_20 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +109519,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_20(info); } }); })); @@ -107151,7 +109563,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,7 +109573,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -107281,7 +109693,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +109705,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -108045,7 +110569,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108177,22 +110701,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -108202,7 +110723,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108300,38 +110821,35 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */ && token.kind !== 99 /* ThisKeyword */) { return undefined; } var parent = token.parent; @@ -108340,14 +110858,22 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + changes.tryInsertJSDocType(sourceFile, parent, typeNode); + } return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -108360,30 +110886,30 @@ var ts; switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); return param; } return undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -108391,9 +110917,9 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } function isApplicableFunctionForInference(declaration) { @@ -108407,36 +110933,62 @@ var ts; } return false; } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, host, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 151 /* PropertySignature */) { + changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var result = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + return typeNode && !param.initializer && !ts.getJSDocType(param) ? __assign({}, inference, { typeNode: typeNode }) : undefined; + }); + changes.tryInsertJSDocParameters(sourceFile, result); + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); var typeIsAccessible = true; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -108447,13 +110999,21 @@ var ts; reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; }); } function inferTypeForVariableFromUsage(token, program, cancellationToken) { @@ -108504,9 +111064,11 @@ var ts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; var isRest = ts.isRestParameter(parameter); + var isOptional = false; for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); continue; } if (isRest) { @@ -108519,10 +111081,14 @@ var ts; } } if (!types.length) { - return undefined; + return { declaration: parameter }; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -108750,16 +111316,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_6.set(name, symbol); }); } @@ -108775,17 +111343,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -109005,7 +111573,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109031,6 +111599,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109481,7 +112249,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_21 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +112268,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_21(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -110126,7 +112894,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110342,7 +113110,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110676,7 +113444,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +113500,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_22 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +113540,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_22(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -111046,7 +113814,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111178,7 +113946,7 @@ var ts; return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; @@ -111322,10 +114090,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_23 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_24 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,12 +114115,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_24(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_23(sourceFile); } } function getNamespaceLikeImport(node) { @@ -111770,7 +114538,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112344,8 +115112,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112523,7 +115291,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112865,8 +115633,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +115672,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112924,7 +115697,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -113039,7 +115812,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +115855,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113162,27 +115935,25 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113389,19 +116160,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 887e98b6f5d..6f680858962 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ const version: string; } @@ -69,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -536,6 +537,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +634,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +671,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -1079,7 +1083,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1808,7 +1812,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -2056,32 +2061,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2490,6 +2495,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2587,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2597,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2698,9 +2695,6 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -3001,6 +2995,16 @@ declare namespace ts { Parameters = 1296, IndexSignatureParameters = 4432 } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3209,17 +3213,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -4171,14 +4185,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4318,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4361,14 +4387,6 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; } /** * Host to create watch with root files and options @@ -4378,6 +4396,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4432,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,184 +4443,11 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4609,7 +4456,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4817,14 +4664,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4882,9 +4722,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5046,9 +4886,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5114,6 +4961,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5266,15 +5115,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 78365f95075..bb0d451215a 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -62,7 +62,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -73,7 +73,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -88,6 +88,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -716,17 +717,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -771,7 +778,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1148,7 +1155,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1275,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1432,7 +1443,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1935,6 +1948,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2029,6 +2046,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2615,6 +2992,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2665,6 +3043,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2734,38 +3114,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2840,14 +3220,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2993,9 +3374,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3394,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3266,25 +3646,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3303,25 +3679,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3565,20 +3940,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3796,17 +4157,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4127,11 +4492,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4742,7 +5108,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5147,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5024,7 +5394,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5421,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5520,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5634,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5730,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5828,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5867,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5545,6 +5934,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5673,10 +6063,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { return token >= 71 /* Identifier */; @@ -5687,136 +6080,85 @@ var ts; return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 117 /* AbstractKeyword */, + any: 119 /* AnyKeyword */, + as: 118 /* AsKeyword */, + boolean: 122 /* BooleanKeyword */, + break: 72 /* BreakKeyword */, + case: 73 /* CaseKeyword */, + catch: 74 /* CatchKeyword */, + class: 75 /* ClassKeyword */, + continue: 77 /* ContinueKeyword */, + const: 76 /* ConstKeyword */ + }, + _a["" + "constructor"] = 123 /* ConstructorKeyword */, + _a.debugger = 78 /* DebuggerKeyword */, + _a.declare = 124 /* DeclareKeyword */, + _a.default = 79 /* DefaultKeyword */, + _a.delete = 80 /* DeleteKeyword */, + _a.do = 81 /* DoKeyword */, + _a.else = 82 /* ElseKeyword */, + _a.enum = 83 /* EnumKeyword */, + _a.export = 84 /* ExportKeyword */, + _a.extends = 85 /* ExtendsKeyword */, + _a.false = 86 /* FalseKeyword */, + _a.finally = 87 /* FinallyKeyword */, + _a.for = 88 /* ForKeyword */, + _a.from = 143 /* FromKeyword */, + _a.function = 89 /* FunctionKeyword */, + _a.get = 125 /* GetKeyword */, + _a.if = 90 /* IfKeyword */, + _a.implements = 108 /* ImplementsKeyword */, + _a.import = 91 /* ImportKeyword */, + _a.in = 92 /* InKeyword */, + _a.infer = 126 /* InferKeyword */, + _a.instanceof = 93 /* InstanceOfKeyword */, + _a.interface = 109 /* InterfaceKeyword */, + _a.is = 127 /* IsKeyword */, + _a.keyof = 128 /* KeyOfKeyword */, + _a.let = 110 /* LetKeyword */, + _a.module = 129 /* ModuleKeyword */, + _a.namespace = 130 /* NamespaceKeyword */, + _a.never = 131 /* NeverKeyword */, + _a.new = 94 /* NewKeyword */, + _a.null = 95 /* NullKeyword */, + _a.number = 134 /* NumberKeyword */, + _a.object = 135 /* ObjectKeyword */, + _a.package = 111 /* PackageKeyword */, + _a.private = 112 /* PrivateKeyword */, + _a.protected = 113 /* ProtectedKeyword */, + _a.public = 114 /* PublicKeyword */, + _a.readonly = 132 /* ReadonlyKeyword */, + _a.require = 133 /* RequireKeyword */, + _a.global = 144 /* GlobalKeyword */, + _a.return = 96 /* ReturnKeyword */, + _a.set = 136 /* SetKeyword */, + _a.static = 115 /* StaticKeyword */, + _a.string = 137 /* StringKeyword */, + _a.super = 97 /* SuperKeyword */, + _a.switch = 98 /* SwitchKeyword */, + _a.symbol = 138 /* SymbolKeyword */, + _a.this = 99 /* ThisKeyword */, + _a.throw = 100 /* ThrowKeyword */, + _a.true = 101 /* TrueKeyword */, + _a.try = 102 /* TryKeyword */, + _a.type = 139 /* TypeKeyword */, + _a.typeof = 103 /* TypeOfKeyword */, + _a.undefined = 140 /* UndefinedKeyword */, + _a.unique = 141 /* UniqueKeyword */, + _a.unknown = 142 /* UnknownKeyword */, + _a.var = 104 /* VarKeyword */, + _a.void = 105 /* VoidKeyword */, + _a.while = 106 /* WhileKeyword */, + _a.with = 107 /* WithKeyword */, + _a.yield = 116 /* YieldKeyword */, + _a.async = 120 /* AsyncKeyword */, + _a.await = 121 /* AwaitKeyword */, + _a.of = 145 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, ">": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -6394,6 +6736,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6423,6 +6766,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6820,9 +7164,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -6878,6 +7222,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7261,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6973,6 +7336,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7478,7 +7846,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7555,6 +7923,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +7946,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7657,22 +8027,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8134,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8001,12 +8364,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,13 +8404,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8408,6 +8779,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8468,6 +8843,7 @@ var ts; case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: case 138 /* SymbolKeyword */: + case 135 /* ObjectKeyword */: case 140 /* UndefinedKeyword */: case 131 /* NeverKeyword */: return true; @@ -9135,18 +9511,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9186,14 +9562,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9216,15 +9592,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9232,26 +9612,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,7 +9640,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9274,30 +9654,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9308,7 +9688,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9352,12 +9732,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9367,9 +9747,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9398,7 +9778,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,11 +9787,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9517,7 +9897,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9559,6 +9939,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9749,6 +10133,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9773,32 +10163,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9857,7 +10251,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10260,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10600,7 +10994,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10614,7 +11008,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10735,7 +11129,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11145,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11035,13 +11429,18 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -11063,15 +11462,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } @@ -11107,10 +11497,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11249,6 +11639,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +11751,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11514,6 +11928,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11525,12 +11941,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11756,13 +12194,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12090,13 +12521,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12108,9 +12539,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12118,10 +12547,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12152,7 +12579,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12198,15 +12625,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12653,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12353,7 +12796,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13699,7 +14155,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14092,6 +14548,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14576,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14589,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14401,8 +14869,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15090,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14684,6 +15157,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14910,36 +15384,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15067,14 +15562,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +15740,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -15333,6 +15844,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15403,6 +15915,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15761,7 +16274,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16443,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -16599,7 +17116,15 @@ var ts; // which would be a candidate for improved error reporting. return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 21 /* OpenBracketToken */: + case 39 /* AsteriskToken */: + case 24 /* DotDotDotToken */: + case 23 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: @@ -17367,8 +17892,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19464,8 +19991,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -20866,7 +21394,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -20991,13 +21519,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21012,7 +21533,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21083,7 +21606,7 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -21264,10 +21787,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21281,14 +21802,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21376,7 +21897,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21391,7 +21912,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21452,7 +21973,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21492,17 +22013,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21530,7 +22051,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21556,9 +22077,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -22399,8 +22918,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +22932,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22461,21 +23015,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22490,6 +23029,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23049,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23062,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23070,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23088,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23198,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23207,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23216,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23242,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23251,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23285,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23298,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23306,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23316,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23332,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23344,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23355,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22874,30 +23440,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23504,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23524,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23570,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23578,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23606,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23634,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +23725,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +23775,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +23795,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +23803,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +23839,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +23882,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +23907,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23619,7 +24249,11 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -23926,7 +24560,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24578,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23980,19 +24629,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +24648,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +24661,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24110,11 +24773,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24161,7 +24819,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +24827,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25041,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24408,10 +25066,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24421,9 +25084,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24431,7 +25110,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24442,16 +25121,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24640,6 +25319,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24656,7 +25341,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25350,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24750,7 +25481,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24770,7 +25502,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24797,11 +25528,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,7 +25548,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24856,14 +25594,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -25086,15 +25828,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +25874,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +25893,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,74 +25904,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25241,8 +25969,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25250,7 +25978,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +25992,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +26009,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,7 +26040,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25352,52 +26081,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25411,12 +26134,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26153,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26191,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,51 +26203,56 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25550,87 +26272,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26402,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,43 +26415,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25695,24 +26460,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26492,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25944,13 +26709,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -25995,7 +26764,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26075,7 +26844,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26153,12 +26923,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26321,6 +27091,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -26419,6 +27190,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -26821,7 +27594,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -27217,7 +27989,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +28009,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27325,9 +28097,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27347,7 +28116,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27572,7 +28341,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27619,7 +28388,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27636,15 +28405,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27717,15 +28486,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27741,7 +28510,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27752,9 +28521,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27835,37 +28604,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27901,7 +28668,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27931,7 +28698,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -27988,7 +28755,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28009,7 +28776,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28035,40 +28802,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,7 +28843,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28090,7 +28856,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28174,8 +28940,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,10 +28956,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28207,7 +28976,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +28994,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,10 +29035,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28278,14 +29047,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28304,9 +29073,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,7 +29111,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(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; })); } @@ -28382,6 +29149,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28457,40 +29227,40 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28511,7 +29281,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28522,25 +29292,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28575,35 +29345,35 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28621,7 +29391,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28632,7 +29402,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28644,7 +29414,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28654,11 +29424,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28674,7 +29444,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28685,7 +29455,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28699,11 +29469,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28711,10 +29481,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28726,7 +29496,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28739,13 +29509,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28758,7 +29528,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28774,13 +29544,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28790,7 +29560,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28807,26 +29577,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28834,18 +29606,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28853,7 +29627,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28864,22 +29638,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28888,7 +29662,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28899,7 +29673,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28908,24 +29682,24 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 199 /* AwaitExpression */: @@ -28999,7 +29773,7 @@ var ts; case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: @@ -29046,8 +29820,8 @@ var ts; // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29056,58 +29830,58 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; case 150 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; @@ -29115,8 +29889,8 @@ var ts; break; case 185 /* ArrayLiteralExpression */: case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; @@ -29127,22 +29901,22 @@ var ts; case 223 /* ForStatement */: case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29164,27 +29938,27 @@ var ts; case 189 /* CallExpression */: case 190 /* NewExpression */: case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; + return 647001409 /* ModuleExcludes */; case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; + return 637535553 /* ParameterExcludes */; case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; + return 653604161 /* ArrowFunctionExcludes */; case 194 /* FunctionExpression */: case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; + return 653620545 /* FunctionExcludes */; case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; + return 639894849 /* VariableDeclarationListExcludes */; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; + return 638121281 /* ClassExcludes */; case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; + return 653616449 /* ConstructorExcludes */; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; + return 653616449 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: @@ -29203,12 +29977,12 @@ var ts; case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; + return 638358849 /* ObjectLiteralExcludes */; case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; + return 637797697 /* CatchClauseExcludes */; case 182 /* ObjectBindingPattern */: case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; + return 637666625 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: case 306 /* PartiallyEmittedExpression */: @@ -29217,9 +29991,9 @@ var ts; return 536872257 /* OuterExpressionExcludes */; case 187 /* PropertyAccessExpression */: case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29434,6 +30208,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30240,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29463,6 +30250,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -29670,8 +30458,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29739,7 +30527,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29769,8 +30558,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29804,6 +30606,7 @@ var ts; var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29815,6 +30618,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +30638,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +30650,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29933,6 +30738,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29975,6 +30782,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +30919,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,7 +30980,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30184,8 +30993,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30206,53 +31016,54 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30360,8 +31171,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30504,7 +31315,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30513,15 +31324,23 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 149 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173 /* ConditionalType */) { @@ -30599,7 +31418,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30609,7 +31428,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30636,7 +31458,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30656,7 +31478,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30730,7 +31552,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30739,7 +31561,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,14 +31616,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30897,9 +31719,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +31740,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30951,7 +31776,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30968,6 +31793,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31037,7 +31865,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +31919,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31147,7 +31975,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31181,7 +32009,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31200,7 +32028,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31215,10 +32043,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32077,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31298,11 +32126,11 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31311,11 +32139,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31331,7 +32159,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32194,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32210,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,6 +32232,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32268,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32287,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32319,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32327,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,24 +32339,23 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -31737,7 +32583,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31837,7 +32683,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +32733,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31952,11 +32801,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +32843,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32102,7 +32961,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32112,7 +32971,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32135,6 +32994,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32217,7 +33079,12 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -32262,13 +33129,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32288,7 +33155,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32355,17 +33222,20 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); @@ -32435,23 +33305,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32533,8 +33403,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +33443,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +33456,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32684,18 +33554,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32823,7 +33688,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +33699,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32875,6 +33740,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32884,12 +33752,22 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32996,7 +33874,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,7 +33889,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33103,6 +33988,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33161,7 +34049,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33345,10 +34233,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34257,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34306,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33426,6 +34316,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33590,27 +34482,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33618,11 +34510,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33670,7 +34562,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33701,16 +34593,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +34628,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33753,8 +34651,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +34660,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,7 +34670,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33783,15 +34681,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +34706,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +34720,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33851,9 +34747,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33876,8 +34770,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +34779,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33899,8 +34793,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33992,9 +34886,9 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -34037,19 +34931,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +34964,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34124,7 +35025,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34152,14 +35053,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34182,7 +35081,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34210,7 +35109,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35118,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35147,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35156,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34431,23 +35322,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34518,7 +35406,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -34529,8 +35419,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34629,7 +35519,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34768,9 +35658,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -34996,7 +35886,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +35906,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35270,7 +36160,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35407,7 +36297,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35430,7 +36320,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35484,6 +36374,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35595,7 +36486,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35765,10 +36656,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35785,7 +36681,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35864,6 +36761,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +36769,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35894,8 +36802,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35910,7 +36818,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35920,9 +36828,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,6 +36877,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35979,14 +36898,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36016,10 +36936,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36110,8 +37030,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -36192,7 +37116,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36292,7 +37216,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37229,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36342,7 +37266,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37297,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36460,7 +37384,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36501,6 +37425,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36537,7 +37462,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36556,8 +37481,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +37527,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36792,10 +37721,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36825,7 +37754,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36880,14 +37809,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +37838,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36904,16 +37847,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -37029,16 +37977,16 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37087,10 +38035,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37118,6 +38066,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37144,7 +38095,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37265,6 +38216,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37333,10 +38292,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38307,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37405,7 +38352,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37433,7 +38380,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37530,10 +38477,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +38486,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37797,7 +38741,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37810,20 +38754,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { @@ -37869,7 +38816,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37887,7 +38834,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37895,20 +38845,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37922,37 +38858,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +38896,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38000,17 +38924,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38188,7 +39123,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39153,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39167,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38374,8 +39309,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38385,7 +39320,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38591,7 +39526,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38692,7 +39627,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +39637,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38761,8 +39696,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +39717,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38819,6 +39768,12 @@ var ts; var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38858,49 +39813,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38974,7 +39945,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39022,8 +39993,9 @@ var ts; return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 131072 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39049,33 +40021,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40121,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40138,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39115,13 +40152,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40195,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40228,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39239,8 +40284,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,9 +40315,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39295,11 +40341,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39325,13 +40371,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39495,10 +40541,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39633,10 +40679,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39692,13 +40738,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39797,7 +40840,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39807,32 +40850,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39849,8 +40866,8 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39888,13 +40905,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +40943,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39950,32 +40971,24 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -40140,6 +41153,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40168,20 +41212,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40199,7 +41248,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40272,6 +41320,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40305,36 +41373,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +41415,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40491,33 +41549,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40549,8 +41580,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40742,6 +41773,52 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41030,8 +42107,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41083,9 +42160,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -41107,10 +42189,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41135,13 +42217,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41153,7 +42239,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41167,11 +42253,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41408,8 +42495,12 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { case 202 /* BinaryExpression */: @@ -41432,44 +42523,49 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41645,7 +42741,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41731,11 +42829,13 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -41784,6 +42884,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41819,7 +42922,22 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41915,33 +43033,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +43074,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ || kind === 155 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +43118,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42011,7 +43142,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +43160,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +43173,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +43186,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +43215,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +43244,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42238,14 +43400,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144 /* Union */) { + if (type.flags & (16 /* Boolean */ | 512 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 /* Unit */ && !(combined & 15794176 /* Instantiable */)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -42289,6 +43467,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42297,8 +43487,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +43503,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42344,13 +43541,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42390,7 +43589,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42476,10 +43675,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42525,6 +43724,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42549,6 +43765,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 /* Union */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144 /* Union */) { var types = type.types; @@ -42567,8 +43786,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42648,8 +43867,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42729,8 +43948,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42833,11 +44052,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,6 +44065,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42869,7 +44096,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42905,15 +44133,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43172,12 +44406,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43188,11 +44432,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43211,6 +44452,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43223,7 +44540,7 @@ var ts; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43240,22 +44557,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43379,8 +44686,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43388,7 +44695,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { if (node.kind === 71 /* Identifier */) { @@ -43436,7 +44743,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43480,8 +44787,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); @@ -43495,8 +44802,8 @@ var ts; while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43509,7 +44816,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43587,6 +44894,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || @@ -43611,22 +44921,42 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (container.kind === 223 /* ForStatement */ && ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; @@ -43768,31 +45098,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,13 +45135,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -43898,16 +45253,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43919,19 +45276,20 @@ var ts; // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; @@ -44039,7 +45397,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44096,7 +45454,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44163,9 +45521,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44212,7 +45582,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,13 +45603,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44249,9 +45626,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,19 +45646,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44299,6 +45703,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +45712,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44329,8 +45731,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44395,47 +45797,36 @@ var ts; case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 71 /* Identifier */: + case 140 /* UndefinedKeyword */: return true; case 187 /* PropertyAccessExpression */: case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 268 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44475,6 +45866,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); + case 199 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); case 189 /* CallExpression */: case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); @@ -44500,7 +45893,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44519,6 +45912,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44527,7 +45926,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44599,11 +45998,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44709,8 +46108,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44746,7 +46145,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +46167,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,7 +46176,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44789,35 +46188,47 @@ var ts; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44907,9 +46318,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44927,7 +46338,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45137,12 +46548,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45159,7 +46572,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +46580,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,7 +46589,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45191,14 +46604,16 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45215,7 +46630,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45248,7 +46663,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45296,7 +46711,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45306,7 +46721,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45373,7 +46788,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +46812,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45619,7 +47034,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45735,7 +47150,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45856,10 +47271,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45904,7 +47319,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46059,6 +47474,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46172,7 +47593,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46277,7 +47698,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46343,7 +47764,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46351,7 +47772,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46472,16 +47893,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46499,7 +47917,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46510,11 +47928,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46545,7 +47963,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,7 +47972,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46612,58 +48030,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46671,12 +48071,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,23 +48082,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46756,36 +48153,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46799,19 +48187,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46819,283 +48208,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 150 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,6 +48297,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47112,7 +48306,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,16 +48320,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47165,36 +48371,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47264,14 +48454,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +48484,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47364,7 +48577,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47375,7 +48588,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47414,17 +48627,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47477,11 +48700,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47493,16 +48716,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47575,11 +48805,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47649,10 +48881,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47676,8 +48909,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47716,8 +48949,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47745,7 +48978,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47824,34 +49057,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,14 +49101,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47924,7 +49158,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,7 +49169,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47945,8 +49179,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49206,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48031,7 +49265,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48156,14 +49390,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +49403,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,15 +49427,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48222,6 +49434,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48307,6 +49530,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48424,10 +49657,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48477,7 +49761,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48547,6 +49831,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48556,8 +49841,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48598,7 +49885,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48803,8 +50089,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48964,7 +50250,7 @@ var ts; if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48990,8 +50276,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49105,7 +50391,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49243,9 +50529,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49260,15 +50546,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49321,8 +50607,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +50617,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49437,7 +50723,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49479,19 +50765,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49522,11 +50804,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49573,15 +50855,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +50881,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +50898,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49633,13 +50923,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49664,7 +50954,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49757,9 +51047,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49789,7 +51076,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50255,7 +51542,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +51573,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50387,8 +51674,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50627,6 +51914,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,13 +51978,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50720,10 +52007,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50953,7 +52240,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50976,7 +52263,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51033,7 +52320,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51291,8 +52578,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51302,7 +52589,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51788,7 +53075,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51871,7 +53158,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51911,7 +53198,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51927,7 +53214,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52301,13 +53588,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52334,9 +53625,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52877,7 +54170,10 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -52888,7 +54184,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52931,7 +54227,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52950,7 +54246,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -53114,6 +54410,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53603,8 +54901,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53615,7 +54913,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53668,14 +54966,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53729,13 +55027,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53766,7 +55064,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +55096,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53846,7 +55144,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54013,7 +55311,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54084,13 +55382,20 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: @@ -54144,9 +55449,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54157,7 +55461,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54260,7 +55563,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54345,12 +55648,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54375,7 +55678,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54401,7 +55704,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54413,7 +55716,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54439,10 +55742,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54458,7 +55761,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54472,7 +55775,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54489,7 +55792,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54568,7 +55871,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54584,6 +55887,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54593,7 +55897,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,30 +55905,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54719,13 +56018,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54786,13 +56104,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54841,7 +56159,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,11 +56172,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54874,7 +56192,7 @@ var ts; // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -54950,7 +56268,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +56281,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +56326,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55052,9 +56389,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55156,7 +56493,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +56508,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +56564,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55266,7 +56607,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55280,9 +56626,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55371,6 +56717,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55415,6 +56764,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55442,31 +56793,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55478,7 +56828,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55852,11 +57202,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56034,6 +57405,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56077,8 +57451,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56295,6 +57671,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56391,26 +57770,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56550,10 +57935,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56584,8 +57970,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60161,6 +61547,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +61575,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -62811,8 +64200,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62878,7 +64267,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63818,7 +65207,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63866,9 +65255,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -65782,7 +67173,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65904,7 +67295,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -66044,6 +67435,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66077,6 +67476,16 @@ var ts; return visitFunctionExpression(node); case 195 /* ArrowFunction */: return visitArrowFunction(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66318,23 +67727,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66352,6 +67771,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66387,6 +67808,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -66409,6 +67832,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66437,13 +67868,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66468,18 +67899,62 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66507,12 +67982,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66535,6 +68010,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66603,6 +68084,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272 /* CatchClause */: return visitCatchClause(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66667,7 +68158,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -66699,7 +68190,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 26 /* CommaToken */) { @@ -66714,7 +68205,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66731,7 +68222,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66828,7 +68319,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66925,25 +68416,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66967,7 +68470,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -66996,6 +68499,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -67018,6 +68523,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67046,13 +68559,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67077,13 +68590,13 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67741,6 +69254,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67921,7 +69439,7 @@ var ts; return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -68519,7 +70037,7 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 /* BinaryExpression */ || superCallExpression.left.kind !== 189 /* CallExpression */) { @@ -68590,7 +70108,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68719,7 +70237,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68907,7 +70425,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69197,19 +70715,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69257,8 +70783,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69513,7 +71039,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -69544,7 +71070,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69570,7 +71112,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69586,7 +71128,69 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 225 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 221 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 222 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223 /* ForStatement */: @@ -69603,165 +71207,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.thisName; } else { // this is top level converted loop so we need to create an alias for 'this' here // NOTE: // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69769,24 +71484,24 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { @@ -69799,8 +71514,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69840,21 +71555,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69994,7 +71717,7 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156 /* GetAccessor */) { @@ -70173,7 +71896,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || node.expression.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -70181,7 +71904,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70228,7 +71951,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70710,7 +72433,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -71135,10 +72858,10 @@ var ts; case 228 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71341,7 +73064,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71465,10 +73188,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71729,10 +73452,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -72399,7 +74122,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72431,10 +74154,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -73516,7 +75239,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +75296,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +75327,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73849,7 +75578,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73916,7 +75645,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74881,7 +76610,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75966,7 +77695,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76773,7 +78502,7 @@ var ts; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -76808,11 +78537,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +78567,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +78585,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +78595,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76937,15 +78667,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,11 +78688,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -76974,6 +78706,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +78725,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +78738,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77038,7 +78775,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77046,13 +78783,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,6 +78804,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77578,10 +79329,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77804,7 +79570,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77818,7 +79584,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -77865,10 +79631,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -78870,7 +80637,7 @@ var ts; emitCallback(node); } if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + ts.performance.mark("beginEmitBodyWithDetachedComments"); } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); @@ -78879,7 +80646,7 @@ var ts; } } if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedComments"); } } function emitLeadingComments(pos, isEmittedNode) { @@ -79100,20 +80867,25 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79136,7 +80908,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79185,26 +80957,31 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -79229,12 +81006,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79963,7 +81740,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79985,7 +81762,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80410,7 +82187,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80621,7 +82398,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81324,13 +83103,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81356,11 +83135,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81525,7 +83309,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81946,19 +83731,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82137,7 +83922,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +84001,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82730,17 +84515,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +84548,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +84558,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +84566,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +84578,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +84590,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +84606,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +84640,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +84667,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +84755,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +84771,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83044,7 +84833,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +84842,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,8 +84866,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83084,21 +84893,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83149,7 +84954,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -83196,7 +85001,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83208,11 +85013,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83299,7 +85105,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +85141,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83378,13 +85186,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83469,8 +85277,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,15 +85289,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83516,15 +85320,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83532,16 +85341,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83564,7 +85372,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,7 +85399,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83657,7 +85469,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83673,7 +85485,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83708,14 +85521,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +85546,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +85561,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +85624,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +85690,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +85781,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84188,7 +86010,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84296,7 +86118,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84352,11 +86174,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84371,6 +86196,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84436,7 +86262,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -84457,6 +86283,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84486,24 +86313,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +86342,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84600,7 +86429,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +86438,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +86458,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,27 +86478,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84677,7 +86498,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84688,22 +86509,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84743,9 +86558,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84755,17 +86571,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +86630,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84850,7 +86665,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84863,9 +86678,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84880,15 +86695,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85079,7 +86894,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,7 +86911,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85104,17 +86922,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85184,7 +86999,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +87009,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +87038,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,11 +87049,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85752,7 +87607,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +87620,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +87801,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86097,7 +87959,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86235,7 +88097,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86575,121 +88438,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - 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]; + return count; } 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; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +88612,6 @@ var ts; result.push.apply(result, targets); return result; } - 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 = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +88629,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +88650,30 @@ var ts; 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 + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // 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); @@ -86827,20 +88682,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; 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)) { // TODO: GH#18217 - 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 (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86855,12 +88708,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86923,13 +88778,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +88846,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,7 +88854,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87031,7 +88904,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +88920,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87081,6 +88954,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + 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 args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +88985,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +88999,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - 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 args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87166,18 +89051,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,9 +89086,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87273,7 +89160,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87311,9 +89199,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +89226,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87519,12 +89407,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87550,7 +89433,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87637,6 +89522,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +89544,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +89562,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +89633,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +89648,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,808 +89669,820 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +90518,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +90530,142 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +90673,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88700,8 +90718,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88776,7 +90794,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +90879,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +90917,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +91008,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89104,6 +91057,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89319,8 +91296,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89377,7 +91355,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89499,6 +91477,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89629,7 +91614,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89993,7 +91978,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +91996,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +92005,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90250,7 +92233,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90364,7 +92347,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +92355,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90514,6 +92497,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); @@ -90883,7 +92873,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +92881,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -90906,14 +92896,14 @@ var ts; ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_7 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_7)) { - clone_7.textSourceNode = node; + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_7)) { - clone_7.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_7, node); + return ts.setTextRange(clone_8, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -91273,7 +93263,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +93272,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -92040,9 +94030,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_10(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92056,27 +94079,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -92085,15 +94096,15 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_11 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); } } if (!foundGlobal) { @@ -92202,7 +94213,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -92235,7 +94246,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -92259,6 +94270,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92366,11 +94389,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92386,7 +94410,7 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) @@ -92471,7 +94495,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +94503,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +94531,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92578,6 +94603,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92663,11 +94691,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92675,16 +94704,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92697,11 +94731,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92715,7 +94749,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92742,6 +94776,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -93150,7 +95189,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +95214,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +95223,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93317,7 +95361,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -93332,9 +95376,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,7 +95413,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93399,12 +95441,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93423,7 +95465,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93444,7 +95486,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93474,7 +95516,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93498,6 +95540,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93733,7 +95782,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93767,14 +95817,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 71 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93928,10 +95983,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93943,6 +95995,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93963,7 +96017,6 @@ var ts; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: case 75 /* ClassKeyword */: case 76 /* ConstKeyword */: case 124 /* DeclareKeyword */: @@ -93978,6 +96031,8 @@ var ts; case 104 /* VarKeyword */: case 116 /* YieldKeyword */: return true; + case 120 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -94151,17 +96206,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94184,7 +96241,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -94256,7 +96313,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94276,14 +96333,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94748,9 +96805,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94795,7 +96849,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +96863,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94876,6 +96930,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -95161,8 +97218,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -95192,8 +97249,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95312,7 +97369,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95457,8 +97514,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95490,9 +97564,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -95505,10 +97579,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95521,28 +97595,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95560,24 +97634,61 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: name + ": " }; + } + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95609,17 +97720,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95635,7 +97746,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95699,11 +97865,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95717,7 +97883,7 @@ var ts; break; case 242 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95725,7 +97891,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95763,7 +97929,7 @@ var ts; 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: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!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); @@ -95894,15 +98060,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -96005,19 +98171,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -96047,7 +98200,7 @@ var ts; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -96062,8 +98215,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -96112,8 +98265,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,7 +98323,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -96197,7 +98350,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96367,12 +98520,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96602,7 +98756,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96660,8 +98814,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96669,39 +98824,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96713,8 +98854,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96727,11 +98886,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96739,19 +98900,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96777,8 +98938,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +99001,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96943,9 +99104,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_12 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +99132,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_12(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +99162,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +99192,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +99234,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97332,6 +99500,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97542,7 +99720,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +99753,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +99816,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97698,7 +99876,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97741,7 +99919,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +99929,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +99944,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -98090,7 +100268,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98416,28 +100594,49 @@ var ts; return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { @@ -99248,13 +101447,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_14 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_14(start); if (typeof state_3 === "object") return state_3.value; } @@ -99794,9 +101993,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; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99805,28 +102004,42 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); @@ -99877,22 +102090,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +102124,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99928,12 +102155,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +102177,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -100238,8 +102465,8 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100248,8 +102475,8 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +102491,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +102508,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100336,7 +102583,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100460,13 +102707,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100489,7 +102736,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100533,13 +102780,13 @@ var ts; switch (statement.kind) { case 217 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); case 219 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100564,10 +102811,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100577,7 +102824,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100596,22 +102843,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100744,13 +103014,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100888,7 +103161,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -101118,7 +103391,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101190,7 +103463,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -101257,6 +103531,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +103605,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_16 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +103624,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_16(opt); } return options; } @@ -102982,13 +105257,13 @@ var ts; var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } @@ -104156,11 +106431,11 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -104175,7 +106450,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -104190,11 +106473,33 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertCommentThenNewline = function (sourceFile, character, position, commentText) { + var token = ts.getTouchingToken(sourceFile, position); + var text = "/**" + commentText + "*/" + this.newLineCharacter + ts.repeatString(" ", character); + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + ChangeTracker.prototype.tryInsertJSDocParameters = function (sourceFile, parameters) { + if (parameters.length === 0) { + return; + } + var parent = parameters[0].declaration.parent; + var indent = ts.getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; + var commentText = "\n"; + for (var _i = 0, parameters_3 = parameters; _i < parameters_3.length; _i++) { + var _a = parameters_3[_i], declaration = _a.declaration, typeNode = _a.typeNode, isOptional = _a.isOptional; + if (ts.isIdentifier(declaration.name)) { + var printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; + commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); + } + } + commentText += ts.repeatString(" ", indent + 1); + this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -104213,6 +106518,25 @@ var ts; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; + ChangeTracker.prototype.tryInsertJSDocType = function (sourceFile, node, type) { + var printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; + var commentText; + if (ts.isGetAccessorDeclaration(node)) { + commentText = " @return {" + printed + "} "; + } + else { + commentText = " @type {" + printed + "} "; + node = node.parent; + } + this.insertCommentThenNewline(sourceFile, ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); + }; + ChangeTracker.prototype.printJSDocParameter = function (indent, printed, name, isOptionalParameter) { + var printName = ts.unescapeLeadingUnderscores(name.escapedText); + if (isOptionalParameter) { + printName = "[" + printName + "]"; + } + return ts.repeatString(" ", indent) + (" * @param {" + printed + "} " + printName + "\n"); + }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); @@ -104256,30 +106580,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +106633,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104427,7 +106758,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104459,7 +106790,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +106798,29 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var _loop_17 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +106833,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_17(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +106872,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +106890,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +106907,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes); + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,9 +106956,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -105399,7 +107742,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105452,57 +107795,63 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_19(statement); } } // Returns the identifiers that are never reassigned in the refactor @@ -105549,7 +107898,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +107912,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +107926,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +107952,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +107975,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +107985,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,7 +108019,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105670,17 +108035,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +108062,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +108078,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,50 +108091,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105774,49 +108159,66 @@ var ts; refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105837,12 +108239,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +108246,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105941,7 +108335,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -106058,7 +108452,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106544,33 +108938,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); 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, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106631,24 +109032,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, 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; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106690,7 +109091,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106738,17 +109139,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +109155,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +109178,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -107009,10 +109421,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107051,7 +109463,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +109492,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_20 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +109519,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_20(info); } }); })); @@ -107151,7 +109563,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,7 +109573,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -107281,7 +109693,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +109705,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -108045,7 +110569,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108177,22 +110701,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -108202,7 +110723,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108300,38 +110821,35 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */ && token.kind !== 99 /* ThisKeyword */) { return undefined; } var parent = token.parent; @@ -108340,14 +110858,22 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + changes.tryInsertJSDocType(sourceFile, parent, typeNode); + } return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -108360,30 +110886,30 @@ var ts; switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); return param; } return undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -108391,9 +110917,9 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } function isApplicableFunctionForInference(declaration) { @@ -108407,36 +110933,62 @@ var ts; } return false; } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, host, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 151 /* PropertySignature */) { + changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var result = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + return typeNode && !param.initializer && !ts.getJSDocType(param) ? __assign({}, inference, { typeNode: typeNode }) : undefined; + }); + changes.tryInsertJSDocParameters(sourceFile, result); + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); var typeIsAccessible = true; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -108447,13 +110999,21 @@ var ts; reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; }); } function inferTypeForVariableFromUsage(token, program, cancellationToken) { @@ -108504,9 +111064,11 @@ var ts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; var isRest = ts.isRestParameter(parameter); + var isOptional = false; for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); continue; } if (isRest) { @@ -108519,10 +111081,14 @@ var ts; } } if (!types.length) { - return undefined; + return { declaration: parameter }; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -108750,16 +111316,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_6.set(name, symbol); }); } @@ -108775,17 +111343,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -109005,7 +111573,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109031,6 +111599,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109481,7 +112249,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_21 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +112268,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_21(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -110126,7 +112894,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110342,7 +113110,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110676,7 +113444,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +113500,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_22 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +113540,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_22(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -111046,7 +113814,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111178,7 +113946,7 @@ var ts; return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; @@ -111322,10 +114090,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_23 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_24 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,12 +114115,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_24(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_23(sourceFile); } } function getNamespaceLikeImport(node) { @@ -111770,7 +114538,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112344,8 +115112,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112523,7 +115291,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112865,8 +115633,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +115672,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112924,7 +115697,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -113039,7 +115812,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +115855,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113162,27 +115935,25 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113389,19 +116160,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index dd81fe55ced..28b6a13abb5 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -86,7 +86,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -101,6 +101,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -729,17 +730,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -784,7 +791,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1161,7 +1168,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1281,6 +1288,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1445,7 +1456,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1948,6 +1961,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2042,6 +2059,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2628,6 +3005,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2678,6 +3056,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2747,38 +3127,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2853,14 +3233,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -3006,9 +3387,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3027,22 +3407,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3279,25 +3659,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3316,25 +3692,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3578,20 +3953,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3809,17 +4170,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4140,11 +4505,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4755,7 +5121,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4794,6 +5160,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5037,7 +5407,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5065,6 +5434,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5156,6 +5533,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5269,7 +5647,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5363,7 +5743,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5461,6 +5841,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5491,9 +5880,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5558,6 +5947,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5686,10 +6076,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { return token >= 71 /* Identifier */; @@ -5700,136 +6093,85 @@ var ts; return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 117 /* AbstractKeyword */, + any: 119 /* AnyKeyword */, + as: 118 /* AsKeyword */, + boolean: 122 /* BooleanKeyword */, + break: 72 /* BreakKeyword */, + case: 73 /* CaseKeyword */, + catch: 74 /* CatchKeyword */, + class: 75 /* ClassKeyword */, + continue: 77 /* ContinueKeyword */, + const: 76 /* ConstKeyword */ + }, + _a["" + "constructor"] = 123 /* ConstructorKeyword */, + _a.debugger = 78 /* DebuggerKeyword */, + _a.declare = 124 /* DeclareKeyword */, + _a.default = 79 /* DefaultKeyword */, + _a.delete = 80 /* DeleteKeyword */, + _a.do = 81 /* DoKeyword */, + _a.else = 82 /* ElseKeyword */, + _a.enum = 83 /* EnumKeyword */, + _a.export = 84 /* ExportKeyword */, + _a.extends = 85 /* ExtendsKeyword */, + _a.false = 86 /* FalseKeyword */, + _a.finally = 87 /* FinallyKeyword */, + _a.for = 88 /* ForKeyword */, + _a.from = 143 /* FromKeyword */, + _a.function = 89 /* FunctionKeyword */, + _a.get = 125 /* GetKeyword */, + _a.if = 90 /* IfKeyword */, + _a.implements = 108 /* ImplementsKeyword */, + _a.import = 91 /* ImportKeyword */, + _a.in = 92 /* InKeyword */, + _a.infer = 126 /* InferKeyword */, + _a.instanceof = 93 /* InstanceOfKeyword */, + _a.interface = 109 /* InterfaceKeyword */, + _a.is = 127 /* IsKeyword */, + _a.keyof = 128 /* KeyOfKeyword */, + _a.let = 110 /* LetKeyword */, + _a.module = 129 /* ModuleKeyword */, + _a.namespace = 130 /* NamespaceKeyword */, + _a.never = 131 /* NeverKeyword */, + _a.new = 94 /* NewKeyword */, + _a.null = 95 /* NullKeyword */, + _a.number = 134 /* NumberKeyword */, + _a.object = 135 /* ObjectKeyword */, + _a.package = 111 /* PackageKeyword */, + _a.private = 112 /* PrivateKeyword */, + _a.protected = 113 /* ProtectedKeyword */, + _a.public = 114 /* PublicKeyword */, + _a.readonly = 132 /* ReadonlyKeyword */, + _a.require = 133 /* RequireKeyword */, + _a.global = 144 /* GlobalKeyword */, + _a.return = 96 /* ReturnKeyword */, + _a.set = 136 /* SetKeyword */, + _a.static = 115 /* StaticKeyword */, + _a.string = 137 /* StringKeyword */, + _a.super = 97 /* SuperKeyword */, + _a.switch = 98 /* SwitchKeyword */, + _a.symbol = 138 /* SymbolKeyword */, + _a.this = 99 /* ThisKeyword */, + _a.throw = 100 /* ThrowKeyword */, + _a.true = 101 /* TrueKeyword */, + _a.try = 102 /* TryKeyword */, + _a.type = 139 /* TypeKeyword */, + _a.typeof = 103 /* TypeOfKeyword */, + _a.undefined = 140 /* UndefinedKeyword */, + _a.unique = 141 /* UniqueKeyword */, + _a.unknown = 142 /* UnknownKeyword */, + _a.var = 104 /* VarKeyword */, + _a.void = 105 /* VoidKeyword */, + _a.while = 106 /* WhileKeyword */, + _a.with = 107 /* WithKeyword */, + _a.yield = 116 /* YieldKeyword */, + _a.async = 120 /* AsyncKeyword */, + _a.await = 121 /* AwaitKeyword */, + _a.of = 145 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, ">": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -6407,6 +6749,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6436,6 +6779,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6833,9 +7177,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -6891,6 +7235,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6929,6 +7274,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6986,6 +7349,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7491,7 +7859,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7568,6 +7936,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7588,7 +7959,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7670,22 +8040,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7790,6 +8147,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8014,12 +8377,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8046,13 +8417,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8421,6 +8792,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8481,6 +8856,7 @@ var ts; case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: case 138 /* SymbolKeyword */: + case 135 /* ObjectKeyword */: case 140 /* UndefinedKeyword */: case 131 /* NeverKeyword */: return true; @@ -9148,18 +9524,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9199,14 +9575,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9229,15 +9605,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9245,26 +9625,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9273,7 +9653,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9287,30 +9667,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9321,7 +9701,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9365,12 +9745,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9380,9 +9760,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9411,7 +9791,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9420,11 +9800,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9530,7 +9910,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9572,6 +9952,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9762,6 +10146,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9786,32 +10176,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9870,7 +10264,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9879,7 +10273,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10613,7 +11007,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10627,7 +11021,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10748,7 +11142,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10764,7 +11158,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11048,13 +11442,18 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -11076,15 +11475,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } @@ -11120,10 +11510,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11262,6 +11652,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11352,6 +11764,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11527,6 +11941,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11538,12 +11954,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11769,13 +12207,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12103,13 +12534,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12121,9 +12552,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12131,10 +12560,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12165,7 +12592,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12211,15 +12638,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12240,6 +12666,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12366,7 +12809,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13712,7 +14168,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14105,6 +14561,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14121,9 +14589,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14135,13 +14602,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14414,8 +14882,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14637,6 +15103,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14697,6 +15170,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14923,36 +15397,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15080,14 +15575,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15258,6 +15753,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -15346,6 +15857,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15416,6 +15928,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15774,7 +16287,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15943,8 +16456,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -16612,7 +17129,15 @@ var ts; // which would be a candidate for improved error reporting. return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 21 /* OpenBracketToken */: + case 39 /* AsteriskToken */: + case 24 /* DotDotDotToken */: + case 23 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: @@ -17380,8 +17905,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19477,8 +20004,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -20879,7 +21407,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -21004,13 +21532,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21025,7 +21546,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21096,7 +21619,7 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -21277,10 +21800,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21294,14 +21815,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21389,7 +21910,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21404,7 +21925,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21465,7 +21986,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21505,17 +22026,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21543,7 +22064,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21569,9 +22090,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -22412,8 +22931,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22427,6 +22945,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22474,21 +23028,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22503,6 +23042,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22521,6 +23062,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22533,6 +23075,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22540,6 +23083,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22557,6 +23101,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22666,6 +23211,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22674,6 +23220,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22682,14 +23229,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22698,6 +23255,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22706,6 +23264,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22739,6 +23298,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22751,6 +23311,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22758,6 +23319,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22767,6 +23329,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22782,6 +23345,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22793,6 +23357,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22803,6 +23368,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22887,30 +23453,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22969,12 +23517,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22987,6 +23537,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23032,6 +23583,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23039,6 +23591,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23066,6 +23619,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23093,7 +23647,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23146,20 +23738,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23195,16 +23788,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23216,7 +23808,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23224,7 +23816,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23260,7 +23852,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23303,9 +23895,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23318,7 +23920,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23632,7 +24262,11 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -23939,7 +24573,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23956,8 +24591,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23993,19 +24642,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24013,7 +24661,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24027,17 +24674,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24123,11 +24786,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24174,7 +24832,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24182,7 +24840,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24396,7 +25054,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24421,10 +25079,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24434,9 +25097,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24444,7 +25123,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24455,16 +25134,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24653,6 +25332,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24669,7 +25354,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24678,48 +25363,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24763,7 +25494,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24783,7 +25515,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24810,11 +25541,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24830,7 +25561,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24869,14 +25607,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -25099,15 +25841,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25145,7 +25887,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25164,7 +25906,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25175,74 +25917,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25254,8 +25982,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25263,7 +25991,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25277,7 +26005,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25294,29 +26022,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25324,7 +26053,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25365,52 +26094,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25424,12 +26147,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25443,40 +26166,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25488,6 +26204,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25499,51 +26216,56 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25563,87 +26285,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25651,11 +26415,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25664,43 +26428,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25708,24 +26473,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25740,9 +26505,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25957,13 +26722,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -26008,7 +26777,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26088,7 +26857,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26166,12 +26936,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26334,6 +27104,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -26432,6 +27203,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -26834,7 +27607,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -27230,7 +28002,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27250,7 +28022,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27338,9 +28110,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27360,7 +28129,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27585,7 +28354,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27632,7 +28401,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27649,15 +28418,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27730,15 +28499,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27754,7 +28523,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27765,9 +28534,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27848,37 +28617,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27914,7 +28681,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27944,7 +28711,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -28001,7 +28768,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28022,7 +28789,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28048,40 +28815,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28090,7 +28856,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28103,7 +28869,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28187,8 +28953,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28200,10 +28969,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28220,7 +28989,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28238,10 +29007,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28279,10 +29048,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28291,14 +29060,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28317,9 +29086,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28357,7 +29124,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(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; })); } @@ -28395,6 +29162,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28470,40 +29240,40 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28524,7 +29294,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28535,25 +29305,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28588,35 +29358,35 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28634,7 +29404,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28645,7 +29415,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28657,7 +29427,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28667,11 +29437,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28687,7 +29457,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28698,7 +29468,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28712,11 +29482,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28724,10 +29494,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28739,7 +29509,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28752,13 +29522,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28771,7 +29541,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28787,13 +29557,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28803,7 +29573,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28820,26 +29590,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28847,18 +29619,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28866,7 +29640,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28877,22 +29651,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28901,7 +29675,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28912,7 +29686,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28921,24 +29695,24 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 199 /* AwaitExpression */: @@ -29012,7 +29786,7 @@ var ts; case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: @@ -29059,8 +29833,8 @@ var ts; // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29069,58 +29843,58 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; case 150 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; @@ -29128,8 +29902,8 @@ var ts; break; case 185 /* ArrayLiteralExpression */: case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; @@ -29140,22 +29914,22 @@ var ts; case 223 /* ForStatement */: case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29177,27 +29951,27 @@ var ts; case 189 /* CallExpression */: case 190 /* NewExpression */: case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; + return 647001409 /* ModuleExcludes */; case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; + return 637535553 /* ParameterExcludes */; case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; + return 653604161 /* ArrowFunctionExcludes */; case 194 /* FunctionExpression */: case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; + return 653620545 /* FunctionExcludes */; case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; + return 639894849 /* VariableDeclarationListExcludes */; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; + return 638121281 /* ClassExcludes */; case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; + return 653616449 /* ConstructorExcludes */; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; + return 653616449 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: @@ -29216,12 +29990,12 @@ var ts; case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; + return 638358849 /* ObjectLiteralExcludes */; case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; + return 637797697 /* CatchClauseExcludes */; case 182 /* ObjectBindingPattern */: case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; + return 637666625 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: case 306 /* PartiallyEmittedExpression */: @@ -29230,9 +30004,9 @@ var ts; return 536872257 /* OuterExpressionExcludes */; case 187 /* PropertyAccessExpression */: case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29447,6 +30221,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29467,7 +30253,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29476,6 +30263,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -29683,8 +30471,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29752,7 +30540,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29782,8 +30571,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29817,6 +30619,7 @@ var ts; var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29828,6 +30631,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29846,6 +30651,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29857,7 +30663,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29946,6 +30751,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29988,6 +30795,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30123,35 +30932,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30184,7 +30993,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30197,8 +31006,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30219,53 +31029,54 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30373,8 +31184,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30517,7 +31328,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30526,15 +31337,23 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 149 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173 /* ConditionalType */) { @@ -30612,7 +31431,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30622,7 +31441,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30649,7 +31471,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30669,7 +31491,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30743,7 +31565,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30752,7 +31574,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30807,14 +31629,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30910,9 +31732,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30931,29 +31753,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30964,7 +31789,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30981,6 +31806,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31050,7 +31878,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31104,7 +31932,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31160,7 +31988,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31194,7 +32022,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31213,7 +32041,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31228,10 +32056,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31262,7 +32090,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31311,11 +32139,11 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31324,11 +32152,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31344,7 +32172,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31379,15 +32207,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31395,9 +32223,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31405,6 +32245,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31434,7 +32281,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31453,7 +32300,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31485,7 +32332,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31493,7 +32340,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31505,24 +32352,23 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -31750,7 +32596,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31850,7 +32696,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31900,7 +32746,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31965,11 +32814,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -32007,7 +32856,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32115,7 +32974,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32125,7 +32984,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32148,6 +33007,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32230,7 +33092,12 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -32275,13 +33142,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32301,7 +33168,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32368,17 +33235,20 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); @@ -32448,23 +33318,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32546,8 +33416,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32586,7 +33456,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32599,7 +33469,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32697,18 +33567,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32836,7 +33701,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32847,7 +33712,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32888,6 +33753,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32897,12 +33765,22 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -33009,7 +33887,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33017,7 +33902,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33116,6 +34001,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33174,7 +34062,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33358,10 +34246,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33382,7 +34270,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33431,6 +34319,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33439,6 +34329,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33603,27 +34495,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33631,11 +34523,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33683,7 +34575,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33714,16 +34606,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33743,16 +34641,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33766,8 +34664,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33775,9 +34673,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33785,7 +34683,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33796,15 +34694,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33823,7 +34719,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33837,10 +34733,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33864,9 +34760,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33889,8 +34783,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33898,7 +34792,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33912,8 +34806,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -34005,9 +34899,9 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -34050,19 +34944,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34076,7 +34977,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34137,7 +35038,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34165,14 +35066,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34195,7 +35094,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34223,7 +35122,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34232,11 +35131,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34261,7 +35160,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34270,22 +35169,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34444,23 +35335,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34531,7 +35419,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -34542,8 +35432,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34642,7 +35532,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34781,9 +35671,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -35009,7 +35899,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35029,7 +35919,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35283,7 +36173,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35420,7 +36310,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35443,7 +36333,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35497,6 +36387,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35608,7 +36499,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35778,10 +36669,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35798,7 +36694,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35877,6 +36774,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35884,8 +36782,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35907,8 +36815,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35923,7 +36831,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35933,9 +36841,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35985,6 +36890,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35992,14 +36911,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36029,10 +36949,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36123,8 +37043,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -36205,7 +37129,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36305,7 +37229,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36318,7 +37242,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36355,7 +37279,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36386,7 +37310,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36473,7 +37397,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36514,6 +37438,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36550,7 +37475,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36569,8 +37494,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36611,7 +37540,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36805,10 +37734,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36838,7 +37767,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36893,14 +37822,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36908,7 +37851,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36917,16 +37860,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -37042,16 +37990,16 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37100,10 +38048,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37131,6 +38079,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37157,7 +38108,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37278,6 +38229,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37346,10 +38305,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37364,15 +38320,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37418,7 +38365,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37446,7 +38393,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37543,10 +38490,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37555,8 +38499,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37810,7 +38754,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37823,20 +38767,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { @@ -37882,7 +38829,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37900,7 +38847,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37908,20 +38858,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37935,37 +38871,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37986,7 +38909,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38013,17 +38937,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38201,7 +39136,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38231,7 +39166,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38245,7 +39180,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38387,8 +39322,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38398,7 +39333,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38604,7 +39539,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38705,7 +39640,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38715,7 +39650,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38774,8 +39709,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38785,30 +39730,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38832,6 +39781,12 @@ var ts; var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38871,49 +39826,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38987,7 +39958,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39035,8 +40006,9 @@ var ts; return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 131072 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39062,33 +40034,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39097,15 +40134,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39114,10 +40151,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39128,13 +40165,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39168,8 +40208,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39201,9 +40241,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39252,8 +40297,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39283,9 +40328,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39308,11 +40354,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39338,13 +40384,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39508,10 +40554,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39646,10 +40692,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39705,13 +40751,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39810,7 +40853,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39820,32 +40863,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39862,8 +40879,8 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39901,13 +40918,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39936,7 +40956,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39963,32 +40984,24 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -40153,6 +41166,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40181,20 +41225,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40212,7 +41261,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40285,6 +41333,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40318,36 +41386,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40370,10 +41428,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40504,33 +41562,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40562,8 +41593,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40755,6 +41786,52 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41043,8 +42120,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41096,9 +42173,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -41120,10 +42202,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41148,13 +42230,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41166,7 +42252,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41180,11 +42266,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41421,8 +42508,12 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { case 202 /* BinaryExpression */: @@ -41445,44 +42536,49 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41658,7 +42754,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41744,11 +42842,13 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -41797,6 +42897,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41832,7 +42935,22 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41928,33 +43046,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41964,12 +43087,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ || kind === 155 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -42000,8 +43131,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42024,7 +43155,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42042,7 +43173,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42055,10 +43186,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42069,16 +43199,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42095,7 +43228,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42124,11 +43257,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42251,14 +43413,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144 /* Union */) { + if (type.flags & (16 /* Boolean */ | 512 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 /* Unit */ && !(combined & 15794176 /* Instantiable */)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -42302,6 +43480,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42310,8 +43500,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42319,8 +43516,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42357,13 +43554,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42403,7 +43602,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42489,10 +43688,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42538,6 +43737,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42562,6 +43778,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 /* Union */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144 /* Union */) { var types = type.types; @@ -42580,8 +43799,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42661,8 +43880,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42742,8 +43961,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42846,11 +44065,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42859,6 +44078,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42882,7 +44109,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42918,15 +44146,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43185,12 +44419,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43201,11 +44445,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43224,6 +44465,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43236,7 +44553,7 @@ var ts; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43253,22 +44570,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43392,8 +44699,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43401,7 +44708,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { if (node.kind === 71 /* Identifier */) { @@ -43449,7 +44756,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43493,8 +44800,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); @@ -43508,8 +44815,8 @@ var ts; while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43522,7 +44829,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43600,6 +44907,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || @@ -43624,22 +44934,42 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (container.kind === 223 /* ForStatement */ && ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; @@ -43781,31 +45111,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43820,13 +45148,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -43911,16 +45266,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43932,19 +45289,20 @@ var ts; // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; @@ -44052,7 +45410,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44109,7 +45467,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44176,9 +45534,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44225,7 +45595,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44246,13 +45616,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44262,9 +45639,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44282,19 +45659,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44312,6 +45716,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44319,10 +45725,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44342,8 +45744,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44408,47 +45810,36 @@ var ts; case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 71 /* Identifier */: + case 140 /* UndefinedKeyword */: return true; case 187 /* PropertyAccessExpression */: case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 268 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44488,6 +45879,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); + case 199 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); case 189 /* CallExpression */: case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); @@ -44513,7 +45906,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44532,6 +45925,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44540,7 +45939,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44612,11 +46011,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44722,8 +46121,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44759,7 +46158,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44781,7 +46180,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44790,7 +46189,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44802,35 +46201,47 @@ var ts; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44920,9 +46331,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44940,7 +46351,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45150,12 +46561,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45172,7 +46585,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45180,7 +46593,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45189,7 +46602,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45204,14 +46617,16 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45228,7 +46643,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45261,7 +46676,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45309,7 +46724,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45319,7 +46734,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45386,7 +46801,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45410,7 +46825,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45632,7 +47047,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45748,7 +47163,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45869,10 +47284,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45917,7 +47332,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46072,6 +47487,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46185,7 +47606,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46290,7 +47711,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46356,7 +47777,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46364,7 +47785,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46485,16 +47906,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46512,7 +47930,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46523,11 +47941,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46558,7 +47976,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46567,7 +47985,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46625,58 +48043,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46684,12 +48084,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46698,23 +48095,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46769,36 +48166,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46812,19 +48200,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46832,283 +48221,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 150 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47117,6 +48310,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47125,7 +48319,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47136,16 +48333,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47178,36 +48384,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47277,14 +48467,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47304,60 +48497,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47377,7 +48590,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47388,7 +48601,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47427,17 +48640,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47490,11 +48713,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47506,16 +48729,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47588,11 +48818,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47662,10 +48894,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47689,8 +48922,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47729,8 +48962,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47758,7 +48991,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47837,34 +49070,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47877,14 +49114,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47937,7 +49171,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47948,7 +49182,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47958,8 +49192,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47985,7 +49219,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48044,7 +49278,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48169,14 +49403,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48185,17 +49416,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48219,15 +49440,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48235,6 +49447,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48320,6 +49543,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48437,10 +49670,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48490,7 +49774,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48560,6 +49844,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48569,8 +49854,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48611,7 +49898,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48816,8 +50102,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48977,7 +50263,7 @@ var ts; if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -49003,8 +50289,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49118,7 +50404,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49256,9 +50542,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49273,15 +50559,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49334,8 +50620,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49344,7 +50630,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49450,7 +50736,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49492,19 +50778,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49535,11 +50817,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49586,15 +50868,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49608,9 +50894,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49621,13 +50911,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49646,13 +50936,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49677,7 +50967,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49770,9 +51060,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49802,7 +51089,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50268,7 +51555,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50299,7 +51586,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50400,8 +51687,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50640,6 +51927,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50697,13 +51991,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50733,10 +52020,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50966,7 +52253,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50989,7 +52276,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51046,7 +52333,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51304,8 +52591,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51315,7 +52602,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51801,7 +53088,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51884,7 +53171,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51924,7 +53211,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51940,7 +53227,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52314,13 +53601,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52347,9 +53638,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52890,7 +54183,10 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -52901,7 +54197,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52944,7 +54240,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52963,7 +54259,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -53127,6 +54423,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53616,8 +54914,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53628,7 +54926,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53681,14 +54979,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53742,13 +55040,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53779,7 +55077,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53811,7 +55109,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53859,7 +55157,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54026,7 +55324,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54097,13 +55395,20 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: @@ -54157,9 +55462,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54170,7 +55474,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54273,7 +55576,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54358,12 +55661,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54388,7 +55691,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54414,7 +55717,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54426,7 +55729,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54452,10 +55755,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54471,7 +55774,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54485,7 +55788,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54502,7 +55805,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54581,7 +55884,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54597,6 +55900,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54606,7 +55910,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54614,30 +55918,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54732,13 +56031,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54799,13 +56117,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54854,7 +56172,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54867,11 +56185,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54887,7 +56205,7 @@ var ts; // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -54963,7 +56281,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54976,7 +56294,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55021,6 +56339,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55065,9 +56402,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55169,7 +56506,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55184,18 +56521,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55238,6 +56577,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55279,7 +56620,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55293,9 +56639,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55384,6 +56730,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55428,6 +56777,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55455,31 +56806,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55491,7 +56841,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55865,11 +57215,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56047,6 +57418,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56090,8 +57464,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56308,6 +57684,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56404,26 +57783,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56563,10 +57948,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56597,8 +57983,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60174,6 +61560,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60187,19 +61588,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -62824,8 +64213,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62891,7 +64280,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63831,7 +65220,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63879,9 +65268,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -65795,7 +67186,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65917,7 +67308,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -66057,6 +67448,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66090,6 +67489,16 @@ var ts; return visitFunctionExpression(node); case 195 /* ArrowFunction */: return visitArrowFunction(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66331,23 +67740,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66365,6 +67784,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66400,6 +67821,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -66422,6 +67845,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66450,13 +67881,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66481,18 +67912,62 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66520,12 +67995,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66548,6 +68023,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66616,6 +68097,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272 /* CatchClause */: return visitCatchClause(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66680,7 +68171,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -66712,7 +68203,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 26 /* CommaToken */) { @@ -66727,7 +68218,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66744,7 +68235,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66841,7 +68332,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66938,25 +68429,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66980,7 +68483,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -67009,6 +68512,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -67031,6 +68536,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67059,13 +68572,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67090,13 +68603,13 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67754,6 +69267,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67934,7 +69452,7 @@ var ts; return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -68532,7 +70050,7 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 /* BinaryExpression */ || superCallExpression.left.kind !== 189 /* CallExpression */) { @@ -68603,7 +70121,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68732,7 +70250,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68920,7 +70438,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69210,19 +70728,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69270,8 +70796,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69526,7 +71052,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -69557,7 +71083,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69583,7 +71125,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69599,7 +71141,69 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 225 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 221 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 222 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223 /* ForStatement */: @@ -69616,165 +71220,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.thisName; } else { // this is top level converted loop so we need to create an alias for 'this' here // NOTE: // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69782,24 +71497,24 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { @@ -69812,8 +71527,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69853,21 +71568,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -70007,7 +71730,7 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156 /* GetAccessor */) { @@ -70186,7 +71909,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || node.expression.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -70194,7 +71917,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70241,7 +71964,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70723,7 +72446,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -71148,10 +72871,10 @@ var ts; case 228 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71354,7 +73077,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71478,10 +73201,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71742,10 +73465,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -72412,7 +74135,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72444,10 +74167,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -73529,7 +75252,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73583,6 +75309,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73613,22 +75340,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73862,7 +75591,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73929,7 +75658,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74894,7 +76623,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75979,7 +77708,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76786,7 +78515,7 @@ var ts; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -76821,11 +78550,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76851,7 +78580,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76869,6 +78598,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76878,10 +78608,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76950,15 +78680,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76970,11 +78701,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -76987,6 +78719,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -77005,8 +78738,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77017,11 +78751,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77051,7 +78788,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77059,13 +78796,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77075,6 +78817,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77591,10 +79342,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77817,7 +79583,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77831,7 +79597,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -77878,10 +79644,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -78883,7 +80650,7 @@ var ts; emitCallback(node); } if (extendedDiagnostics) { - ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + ts.performance.mark("beginEmitBodyWithDetachedComments"); } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); @@ -78892,7 +80659,7 @@ var ts; } } if (extendedDiagnostics) { - ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedComments"); } } function emitLeadingComments(pos, isEmittedNode) { @@ -79113,20 +80880,25 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79149,7 +80921,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79198,26 +80970,31 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -79242,12 +81019,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79976,7 +81753,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79998,7 +81775,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80423,7 +82200,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80634,7 +82411,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81337,13 +83116,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81369,11 +83148,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81538,7 +83322,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81959,19 +83744,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82150,7 +83935,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82229,7 +84014,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82743,17 +84528,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82769,7 +84561,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82779,7 +84571,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82787,8 +84579,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82799,8 +84591,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82811,11 +84603,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82827,36 +84619,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82864,8 +84653,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82891,7 +84680,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82979,8 +84768,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82995,11 +84784,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83057,7 +84846,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83066,6 +84855,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83086,8 +84879,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83097,21 +84906,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83162,7 +84967,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -83209,7 +85014,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83221,11 +85026,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83312,7 +85118,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83346,9 +85154,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83391,13 +85199,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83482,8 +85290,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83491,15 +85302,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83529,15 +85333,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83545,16 +85354,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83577,7 +85385,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83604,7 +85412,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83670,7 +85482,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83686,7 +85498,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83721,14 +85534,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83739,11 +85559,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83753,12 +85574,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83815,7 +85637,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83881,9 +85703,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83972,7 +85794,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84201,7 +86023,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84309,7 +86131,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84365,11 +86187,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84384,6 +86209,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84449,7 +86275,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -84470,6 +86296,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84499,24 +86326,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84526,7 +86355,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84613,7 +86442,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84622,7 +86451,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84642,7 +86471,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84662,27 +86491,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84690,7 +86511,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84701,22 +86522,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84756,9 +86571,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84768,17 +86584,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84828,15 +86643,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84863,7 +86678,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84876,9 +86691,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84893,15 +86708,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85092,7 +86907,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85109,7 +86924,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85117,17 +86935,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85197,7 +87012,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85207,6 +87022,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85230,7 +87051,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85241,11 +87062,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85765,7 +87620,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85778,7 +87633,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85952,16 +87814,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86110,7 +87972,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86248,7 +88110,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86588,121 +88451,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - 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]; + return count; } 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; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86766,16 +88625,6 @@ var ts; result.push.apply(result, targets); return result; } - 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 = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86793,7 +88642,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86813,25 +88663,30 @@ var ts; 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 + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // 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); @@ -86840,20 +88695,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; 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)) { // TODO: GH#18217 - 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 (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86868,12 +88721,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86936,13 +88791,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86981,11 +88859,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86994,7 +88867,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87044,7 +88917,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87060,7 +88933,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87094,6 +88967,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + 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 args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87106,7 +88998,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87120,17 +89012,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - 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 args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87179,18 +89064,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87213,9 +89099,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87286,7 +89173,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87324,9 +89212,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87351,7 +89239,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87532,12 +89420,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87563,7 +89446,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87650,6 +89535,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87670,7 +89557,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87687,94 +89575,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87787,7 +89646,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87798,13 +89661,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87815,808 +89682,820 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88652,7 +90531,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88660,6 +90541,142 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.js.map "use strict"; /* @internal */ @@ -88671,6 +90688,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88715,8 +90733,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88791,7 +90809,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88876,7 +90894,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -89005,71 +91023,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); //# sourceMappingURL=jsTyping.js.map "use strict"; var ts; @@ -89277,8 +91230,10 @@ var ts; } var info = ts.getProperty(npmLock.dependencies, key); var version_1 = info && info.version; - var semver = ts.Semver.parse(version_1); // TODO: GH#18217 - var newTyping = { typingLocation: typingFile, version: semver }; + if (!version_1) { + continue; + } + var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) }; this.packageNameToTypingLocation.set(packageName, newTyping); } } @@ -89380,7 +91335,7 @@ var ts; } // packageName is guaranteed to exist in typesRegistry by filterTypings var distTags = _this.typesRegistry.get(packageName); - var newVersion = ts.Semver.parse(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]); + var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]); var newTyping = { typingLocation: typingFile, version: newVersion }; _this.packageNameToTypingLocation.set(packageName, newTyping); installedTypingFiles.push(typingFile); @@ -89559,16 +91514,17 @@ var ts; function FileLog(logFile) { var _this = this; this.logFile = logFile; - this.logEnabled = true; this.isEnabled = function () { - return _this.logEnabled && _this.logFile !== undefined; + return typeof _this.logFile === "string"; }; this.writeLine = function (text) { + if (typeof _this.logFile !== "string") + return; try { fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine); } catch (e) { - _this.logEnabled = false; + _this.logFile = undefined; } }; } @@ -89678,6 +91634,11 @@ var ts; } break; } + case "inspectValue": { + var response = { kind: server.ActionValueInspected, result: ts.inspectModule(req.options.fileNameToRequire) }; + _this.sendResponse(response); + break; + } default: ts.Debug.assertNever(req); } diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index aaf6a7101a8..23d0bae7b27 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -68,7 +68,7 @@ "A_rest_parameter_cannot_have_an_initializer_1048": "rest 参数不能具有初始化表达式。", "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 参数必须是参数列表中的最后一个参数。", "A_rest_parameter_must_be_of_an_array_type_2370": "rest 参数必须是数组类型。", - "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式可能不具有尾随逗号。", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式不可带尾随逗号。", "A_return_statement_can_only_be_used_within_a_function_body_1108": "\"return\" 语句只能在函数体中使用。", "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "一系列条目,这些条目将重新映射导入内容,以查找与 \"baseUrl\" 有关的位置。", "A_set_accessor_cannot_have_a_return_type_annotation_1095": "\"set\" 访问器不能具有返回类型批注。", @@ -161,7 +161,7 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引签名参数不能具有可访问性修饰符。", "An_index_signature_parameter_cannot_have_an_initializer_1020": "索引签名参数不能具有初始化表达式。", "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引签名参数必须具有类型批注。", - "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改而编写“[{0}: {1}]:{2}”。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改为编写“[{0}: {1}]:{2}”。", "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引签名参数类型不能为联合类型。请考虑改用映射的对象类型。", "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引签名参数类型必须为 \"string\" 或 \"number\"。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "接口只能扩展具有可选类型参数的标识符/限定名称。", @@ -628,7 +628,7 @@ "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": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。", "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": "没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "在没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。", "Options_0_and_1_cannot_be_combined_6370": "选项“{0}”与“{1}”不能组合在一起。", "Options_Colon_6027": "选项:", "Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。", diff --git a/package.json b/package.json index 55acc40268d..86872c57c6b 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "typescript", "author": "Microsoft Corp.", - "homepage": "http://typescriptlang.org/", - "version": "3.1.0", + "homepage": "https://www.typescriptlang.org/", + "version": "3.2.0", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ @@ -75,6 +75,7 @@ "gulp-typescript": "latest", "istanbul": "latest", "jake": "latest", + "lodash": "4.17.10", "merge2": "latest", "minimist": "latest", "mkdirp": "latest", diff --git a/scripts/build/upToDate.js b/scripts/build/upToDate.js index f92fd6b503a..c3abb5d1013 100644 --- a/scripts/build/upToDate.js +++ b/scripts/build/upToDate.js @@ -4,7 +4,7 @@ const fs = require("fs"); const log = require("fancy-log"); // was `require("gulp-util").log (see https://github.com/gulpjs/gulp-util) const ts = require("../../lib/typescript"); const { Duplex } = require("stream"); -const chalk = require("./chalk"); +const chalk = /**@type {*} */(require("chalk")); const Vinyl = require("vinyl"); /** @@ -14,7 +14,7 @@ const Vinyl = require("vinyl"); * @param {UpToDateOptions} [options] * * @typedef UpToDateOptions - * @property {boolean} [verbose] + * @property {boolean | "minimal"} [verbose] * @property {(configFilePath: string) => ParsedCommandLine | undefined} [parseProject] */ function upToDate(parsedProject, options) { @@ -47,9 +47,9 @@ function upToDate(parsedProject, options) { cb(); }, final(cb) { - const status = ts.getUpToDateStatus(upToDateHost, parsedProject); + const status = getUpToDateStatus(upToDateHost, parsedProject); reportStatus(parsedProject, status, options); - if (status.type !== ts.UpToDateStatusType.UpToDate) { + if (status.type !== UpToDateStatusType.UpToDate) { for (const input of inputs) duplex.push(input); } duplex.push(null); @@ -88,11 +88,25 @@ function formatMessage(message, ...args) { /** * @param {ParsedCommandLine} project * @param {UpToDateStatus} status - * @param {{verbose?: boolean}} options + * @param {{verbose?: boolean | "minimal"}} options */ function reportStatus(project, status, options) { + switch (options.verbose) { + case "minimal": + switch (status.type) { + case UpToDateStatusType.UpToDate: + log.info(`Project '${fileName(project.options.configFilePath)}' is up to date.`); + break; + default: + log.info(`Project '${fileName(project.options.configFilePath)}' is out of date, rebuilding...`); + break; + } + break; + case true: + /**@type {*}*/(ts).formatUpToDateStatus(project.options.configFilePath, status, fileName, formatMessage); + break; + } if (!options.verbose) return; - ts.formatUpToDateStatus(project.options.configFilePath, status, fileName, formatMessage); } /** @@ -120,12 +134,302 @@ function formatStringFromArgs(text, args, baseIndex = 0) { return text.replace(/{(\d+)}/g, (_match, index) => args[+index + baseIndex]); } +const minimumDate = new Date(-8640000000000000); +const maximumDate = new Date(8640000000000000); +const missingFileModifiedTime = new Date(0); + +/** + * @typedef {0} UpToDateStatusType.Unbuildable + * @typedef {1} UpToDateStatusType.UpToDate + * @typedef {2} UpToDateStatusType.UpToDateWithUpstreamTypes + * @typedef {3} UpToDateStatusType.OutputMissing + * @typedef {4} UpToDateStatusType.OutOfDateWithSelf + * @typedef {5} UpToDateStatusType.OutOfDateWithUpstream + * @typedef {6} UpToDateStatusType.UpstreamOutOfDate + * @typedef {7} UpToDateStatusType.UpstreamBlocked + * @typedef {8} UpToDateStatusType.ComputingUpstream + * @typedef {9} UpToDateStatusType.ContainerOnly + * @enum {UpToDateStatusType.Unbuildable | UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes | UpToDateStatusType.OutputMissing | UpToDateStatusType.OutOfDateWithSelf | UpToDateStatusType.OutOfDateWithUpstream | UpToDateStatusType.UpstreamOutOfDate | UpToDateStatusType.UpstreamBlocked | UpToDateStatusType.ComputingUpstream | UpToDateStatusType.ContainerOnly} + */ +const UpToDateStatusType = { + Unbuildable: /** @type {0} */(0), + UpToDate: /** @type {1} */(1), + UpToDateWithUpstreamTypes: /** @type {2} */(2), + OutputMissing: /** @type {3} */(3), + OutOfDateWithSelf: /** @type {4} */(4), + OutOfDateWithUpstream: /** @type {5} */(5), + UpstreamOutOfDate: /** @type {6} */(6), + UpstreamBlocked: /** @type {7} */(7), + ComputingUpstream: /** @type {8} */(8), + ContainerOnly: /** @type {9} */(9), +}; + +/** + * @param {Date} date1 + * @param {Date} date2 + * @returns {Date} + */ +function newer(date1, date2) { + return date2 > date1 ? date2 : date1; +} + +/** + * @param {UpToDateHost} host + * @param {ParsedCommandLine | undefined} project + * @returns {UpToDateStatus} + */ +function getUpToDateStatus(host, project) { + if (project === undefined) return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + const prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; + if (prior !== undefined) { + return prior; + } + const actual = getUpToDateStatusWorker(host, project); + if (host.setLastStatus) { + host.setLastStatus(project.options.configFilePath, actual); + } + return actual; +} + +/** + * @param {UpToDateHost} host + * @param {ParsedCommandLine | undefined} project + * @returns {UpToDateStatus} + */ +function getUpToDateStatusWorker(host, project) { + /** @type {string} */ + let newestInputFileName = undefined; + let newestInputFileTime = minimumDate; + // Get timestamps of input files + for (const inputFile of project.fileNames) { + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: `${inputFile} does not exist` + }; + } + + const inputTime = host.getModifiedTime(inputFile) || missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + + // Collect the expected outputs of this project + const outputs = /**@type {string[]}*/(/**@type {*}*/(ts).getAllProjectOutputs(project)); + + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + + // Now see if all outputs are newer than the newest input + let oldestOutputFileName = "(none)"; + let oldestOutputFileTime = maximumDate; + let newestOutputFileName = "(none)"; + let newestOutputFileTime = minimumDate; + /** @type {string | undefined} */ + let missingOutputFileName; + let newestDeclarationFileContentChangedTime = minimumDate; + let isOutOfDateWithInputs = false; + for (const output of outputs) { + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + + const outputTime = host.getModifiedTime(output) || missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (path.extname(output) === ".d.ts") { + const unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + const outputModifiedTime = host.getModifiedTime(output) || missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + + let pseudoUpToDate = false; + let usesPrepend = false; + /** @type {string | undefined} */ + let upstreamChangedProject; + if (project.projectReferences) { + if (host.setLastStatus) host.setLastStatus(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (const ref of project.projectReferences) { + usesPrepend = usesPrepend || !!(ref.prepend); + const resolvedRef = ts.resolveProjectReferencePath(host, ref); + const parsedRef = host.parseConfigFile ? host.parseConfigFile(resolvedRef) : ts.getParsedCommandLineOfConfigFile(resolvedRef, {}, parseConfigHost); + const refStatus = getUpToDateStatus(host, parsedRef); + + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + + // We have an output older than an upstream output - we are out of date + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName + }; + } + + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime, + newestInputFileTime, + newestOutputFileTime, + newestInputFileName, + newestOutputFileName, + oldestOutputFileName + }; +} + +const parseConfigHost = { + useCaseSensitiveFileNames: true, + getCurrentDirectory: () => process.cwd(), + readDirectory: (file) => fs.readdirSync(file), + fileExists: file => fs.existsSync(file) && fs.statSync(file).isFile(), + readFile: file => fs.readFileSync(file, "utf8"), + onUnRecoverableConfigFileDiagnostic: () => undefined +}; + /** * @typedef {import("vinyl")} File * @typedef {import("../../lib/typescript").ParsedCommandLine & { options: CompilerOptions }} ParsedCommandLine * @typedef {import("../../lib/typescript").CompilerOptions & { configFilePath?: string }} CompilerOptions - * @typedef {import("../../lib/typescript").UpToDateHost} UpToDateHost - * @typedef {import("../../lib/typescript").UpToDateStatus} UpToDateStatus * @typedef {import("../../lib/typescript").DiagnosticMessage} DiagnosticMessage + * @typedef UpToDateHost + * @property {(fileName: string) => boolean} fileExists + * @property {(fileName: string) => Date} getModifiedTime + * @property {(fileName: string) => Date} [getUnchangedTime] + * @property {(configFilePath: string) => ParsedCommandLine | undefined} parseConfigFile + * @property {(configFilePath: string) => UpToDateStatus} [getLastStatus] + * @property {(configFilePath: string, status: UpToDateStatus) => void} [setLastStatus] + * + * @typedef Status.Unbuildable + * @property {UpToDateStatusType.Unbuildable} type + * @property {string} reason + * + * @typedef Status.ContainerOnly + * @property {UpToDateStatusType.ContainerOnly} type + * + * @typedef Status.UpToDate + * @property {UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes} type + * @property {Date} [newestInputFileTime] + * @property {string} [newestInputFileName] + * @property {Date} [newestDeclarationFileContentChangedTime] + * @property {Date} [newestOutputFileTime] + * @property {string} [newestOutputFileName] + * @property {string} [oldestOutputFileName] + * + * @typedef Status.OutputMissing + * @property {UpToDateStatusType.OutputMissing} type + * @property {string} missingOutputFileName + * + * @typedef Status.OutOfDateWithSelf + * @property {UpToDateStatusType.OutOfDateWithSelf} type + * @property {string} outOfDateOutputFileName + * @property {string} newerInputFileName + * + * @typedef Status.UpstreamOutOfDate + * @property {UpToDateStatusType.UpstreamOutOfDate} type + * @property {string} upstreamProjectName + * + * @typedef Status.UpstreamBlocked + * @property {UpToDateStatusType.UpstreamBlocked} type + * @property {string} upstreamProjectName + * + * @typedef Status.ComputingUpstream + * @property {UpToDateStatusType.ComputingUpstream} type + * + * @typedef Status.OutOfDateWithUpstream + * @property {UpToDateStatusType.OutOfDateWithUpstream} type + * @property {string} outOfDateOutputFileName + * @property {string} newerProjectName + + * @typedef {Status.Unbuildable | Status.ContainerOnly | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ComputingUpstream | Status.OutOfDateWithUpstream} UpToDateStatus */ void 0; \ No newline at end of file diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index ea8fb3eea8d..292bfe51340 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -234,13 +234,17 @@ namespace ts { } if (symbolFlags & SymbolFlags.Value) { - const { valueDeclaration } = symbol; - if (!valueDeclaration || - (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - symbol.valueDeclaration = node; - } + setValueDeclaration(symbol, node); + } + } + + function setValueDeclaration(symbol: Symbol, node: Declaration): void { + const { valueDeclaration } = symbol; + if (!valueDeclaration || + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } @@ -288,7 +292,7 @@ namespace ts { // module.exports = ... return InternalSymbolName.ExportEquals; case SyntaxKind.BinaryExpression: - if (getSpecialPropertyAssignmentKind(node as BinaryExpression) === SpecialPropertyAssignmentKind.ModuleExports) { + if (getAssignmentDeclarationKind(node as BinaryExpression) === AssignmentDeclarationKind.ModuleExports) { // module.exports = ... return InternalSymbolName.ExportEquals; } @@ -374,8 +378,8 @@ namespace ts { // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name)); } - else if (!(includes & SymbolFlags.Variable && symbol.flags & SymbolFlags.JSContainer)) { - // JSContainers are allowed to merge with variables, no matter what other flags they have. + else if (!(includes & SymbolFlags.Variable && symbol.flags & SymbolFlags.Assignment)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (isNamedDeclaration(node)) { node.name.parent = node; } @@ -461,7 +465,7 @@ namespace ts { // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (isJSDocTypeAlias(node)) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypeAlias(node)) { if (hasModifier(node, ModifierFlags.Default) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! @@ -636,6 +640,7 @@ namespace ts { function bindChildrenWorker(node: Node): void { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -1176,7 +1181,6 @@ namespace ts { } const preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow!, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow!, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); const clause = clauses[i]; @@ -2009,7 +2013,7 @@ namespace ts { function bindJSDoc(node: Node) { if (hasJSDocNodes(node)) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { for (const j of node.jsDoc!) { bind(j); } @@ -2075,7 +2079,7 @@ namespace ts { if (isSpecialPropertyDeclaration(node as PropertyAccessExpression)) { bindSpecialPropertyDeclaration(node as PropertyAccessExpression); } - if (isInJavaScriptFile(node) && + if (isInJSFile(node) && file.commonJsModuleIndicator && isModuleExportsPropertyAccessExpression(node as PropertyAccessExpression) && !lookupSymbolForNameWorker(blockScopeContainer, "module" as __String)) { @@ -2084,27 +2088,27 @@ namespace ts { } break; case SyntaxKind.BinaryExpression: - const specialKind = getSpecialPropertyAssignmentKind(node as BinaryExpression); + const specialKind = getAssignmentDeclarationKind(node as BinaryExpression); switch (specialKind) { - case SpecialPropertyAssignmentKind.ExportsProperty: + case AssignmentDeclarationKind.ExportsProperty: bindExportsPropertyAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.ModuleExports: + case AssignmentDeclarationKind.ModuleExports: bindModuleExportsAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.PrototypeProperty: bindPrototypePropertyAssignment((node as BinaryExpression).left as PropertyAccessEntityNameExpression, node); break; - case SpecialPropertyAssignmentKind.Prototype: + case AssignmentDeclarationKind.Prototype: bindPrototypeAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ThisProperty: bindThisPropertyAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.Property: + case AssignmentDeclarationKind.Property: bindSpecialPropertyAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.None: // Nothing to do break; default: @@ -2184,7 +2188,7 @@ namespace ts { return bindFunctionExpression(node); case SyntaxKind.CallExpression: - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { bindCallExpression(node); } break; @@ -2286,14 +2290,19 @@ namespace ts { bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node)!); } else { - const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) + const flags = exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? SymbolFlags.Alias // An export default clause with any other expression exports a value : SymbolFlags.Property; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.All); + const symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.All); + + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } @@ -2301,27 +2310,17 @@ namespace ts { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Modifiers_cannot_appear_here)); } - - if (node.parent.kind !== SyntaxKind.SourceFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + const diag = !isSourceFile(node.parent) ? Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !isExternalModule(node.parent) ? Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - const parent = node.parent as SourceFile; - - if (!isExternalModule(parent)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - - if (!parent.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); } - - file.symbol.globalExports = file.symbol.globalExports || createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); } function bindExportDeclaration(node: ExportDeclaration) { @@ -2361,7 +2360,7 @@ namespace ts { const lhs = node.left as PropertyAccessEntityNameExpression; const symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, (id, symbol) => { if (symbol) { - addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.JSContainer); + addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.Assignment); } return symbol; }); @@ -2394,7 +2393,7 @@ namespace ts { } function bindThisPropertyAssignment(node: BinaryExpression | PropertyAccessExpression) { - Debug.assert(isInJavaScriptFile(node)); + Debug.assert(isInJSFile(node)); const thisContainer = getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case SyntaxKind.FunctionDeclaration: @@ -2456,7 +2455,7 @@ namespace ts { node.left.parent = node; node.right.parent = node; const lhs = node.left as PropertyAccessEntityNameExpression; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** @@ -2482,7 +2481,7 @@ namespace ts { const lhs = node.left as PropertyAccessEntityNameExpression; // Class declarations in Typescript do not allow property declarations const parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!isInJavaScriptFile(node) && !isFunctionSymbol(parentSymbol)) { + if (!isInJSFile(node) && !isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -2513,21 +2512,23 @@ namespace ts { const isToplevel = isBinaryExpression(propertyAccess.parent) ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === SyntaxKind.SourceFile : propertyAccess.parent.parent.kind === SyntaxKind.SourceFile; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & SymbolFlags.Namespace)) && isToplevel) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & SymbolFlags.Namespace))) { // make symbols or add declarations for intermediate containers - const flags = SymbolFlags.Module | SymbolFlags.JSContainer; - const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.JSContainer; + const flags = SymbolFlags.Module | SymbolFlags.Assignment; + const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.Assignment; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, (id, symbol, parent) => { if (symbol) { addDeclarationToSymbol(symbol, id, flags); return symbol; } else { - return declareSymbol(parent ? parent.exports! : container.locals!, parent, id, flags, excludeFlags); + const table = parent ? parent.exports! : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = createSymbolTable()); + return declareSymbol(table, parent, id, flags, excludeFlags); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } @@ -2536,14 +2537,14 @@ namespace ts { (namespaceSymbol.members || (namespaceSymbol.members = createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = createSymbolTable())); - const isMethod = isFunctionLikeDeclaration(getAssignedJavascriptInitializer(propertyAccess)!); + const isMethod = isFunctionLikeDeclaration(getAssignedExpandoInitializer(propertyAccess)!); const includes = isMethod ? SymbolFlags.Method : SymbolFlags.Property; const excludes = isMethod ? SymbolFlags.MethodExcludes : SymbolFlags.PropertyExcludes; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | SymbolFlags.JSContainer, excludes & ~SymbolFlags.JSContainer); + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | SymbolFlags.Assignment, excludes & ~SymbolFlags.Assignment); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -2552,7 +2553,7 @@ namespace ts { * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol: Symbol): boolean { + function isExpandoSymbol(symbol: Symbol): boolean { if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.NamespaceModule)) { return true; } @@ -2565,7 +2566,7 @@ namespace ts { init = init && getRightMostAssignedExpression(init); if (init) { const isPrototypeAssignment = isPrototypeAccess(isVariableDeclaration(node) ? node.name : isBinaryExpression(node) ? node.left : node); - return !!getJavascriptInitializer(isBinaryExpression(init) && init.operatorToken.kind === SyntaxKind.BarBarToken ? init.right : init, isPrototypeAssignment); + return !!getExpandoInitializer(isBinaryExpression(init) && init.operatorToken.kind === SyntaxKind.BarBarToken ? init.right : init, isPrototypeAssignment); } return false; } @@ -2657,7 +2658,7 @@ namespace ts { } if (!isBindingPattern(node.name)) { - const isEnum = !!getJSDocEnumTag(node); + const isEnum = isInJSFile(node) && !!getJSDocEnumTag(node); const enumFlags = (isEnum ? SymbolFlags.RegularEnum : SymbolFlags.None); const enumExcludes = (isEnum ? SymbolFlags.RegularEnumExcludes : SymbolFlags.None); if (isBlockOrCatchScoped(node)) { @@ -2892,6 +2893,9 @@ namespace ts { if (local) { return local.exportSymbol || local; } + if (isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } @@ -2996,7 +3000,7 @@ namespace ts { transformFlags |= TransformFlags.AssertTypeScript; } - if (subtreeFlags & TransformFlags.ContainsSpread + if (subtreeFlags & TransformFlags.ContainsRestOrSpread || (expression.transformFlags & (TransformFlags.Super | TransformFlags.ContainsSuper))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. @@ -3027,7 +3031,7 @@ namespace ts { if (node.typeArguments) { transformFlags |= TransformFlags.AssertTypeScript; } - if (subtreeFlags & TransformFlags.ContainsSpread) { + if (subtreeFlags & TransformFlags.ContainsRestOrSpread) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= TransformFlags.AssertES2015; @@ -3070,18 +3074,18 @@ namespace ts { // syntax. if (node.questionToken || node.type - || subtreeFlags & TransformFlags.ContainsDecorators + || (subtreeFlags & TransformFlags.ContainsTypeScriptClassSyntax && some(node.decorators)) || isThisIdentifier(name)) { transformFlags |= TransformFlags.AssertTypeScript; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (hasModifier(node, ModifierFlags.ParameterPropertyModifier)) { - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsParameterPropertyAssignments; + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsTypeScriptClassSyntax; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3134,7 +3138,7 @@ namespace ts { // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) + if ((subtreeFlags & TransformFlags.ContainsTypeScriptClassSyntax) || node.typeParameters) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -3156,7 +3160,7 @@ namespace ts { // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask + if (subtreeFlags & TransformFlags.ContainsTypeScriptClassSyntax || node.typeParameters) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -3233,7 +3237,7 @@ namespace ts { } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3257,7 +3261,7 @@ namespace ts { } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3288,7 +3292,7 @@ namespace ts { } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3303,7 +3307,7 @@ namespace ts { // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || isComputedPropertyName(node.name)) { - transformFlags |= TransformFlags.ContainsPropertyInitializer; + transformFlags |= TransformFlags.ContainsTypeScriptClassSyntax; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -3337,7 +3341,7 @@ namespace ts { } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3379,7 +3383,7 @@ namespace ts { } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3420,7 +3424,7 @@ namespace ts { } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3440,7 +3444,9 @@ namespace ts { // ES6 syntax, and requires a lexical `this` binding. if (transformFlags & TransformFlags.Super) { transformFlags ^= TransformFlags.Super; - transformFlags |= TransformFlags.ContainsSuper; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= TransformFlags.ContainsSuper | TransformFlags.ContainsES2017 | TransformFlags.ContainsESNext; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -3456,7 +3462,9 @@ namespace ts { // ES6 syntax, and requires a lexical `this` binding. if (expressionFlags & TransformFlags.Super) { transformFlags &= ~TransformFlags.Super; - transformFlags |= TransformFlags.ContainsSuper; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= TransformFlags.ContainsSuper | TransformFlags.ContainsES2017 | TransformFlags.ContainsESNext; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -3468,7 +3476,7 @@ namespace ts { transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & TransformFlags.ContainsObjectRest) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { transformFlags |= TransformFlags.AssertESNext; } @@ -3717,11 +3725,11 @@ namespace ts { break; case SyntaxKind.SpreadElement: - transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsSpread; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsRestOrSpread; break; case SyntaxKind.SpreadAssignment: - transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectSpread; + transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRestOrSpread; break; case SyntaxKind.SuperKeyword: @@ -3737,8 +3745,8 @@ namespace ts { case SyntaxKind.ObjectBindingPattern: transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; - if (subtreeFlags & TransformFlags.ContainsRest) { - transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRest; + if (subtreeFlags & TransformFlags.ContainsRestOrSpread) { + transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRestOrSpread; } excludeFlags = TransformFlags.BindingPatternExcludes; break; @@ -3751,13 +3759,13 @@ namespace ts { case SyntaxKind.BindingElement: transformFlags |= TransformFlags.AssertES2015; if ((node).dotDotDotToken) { - transformFlags |= TransformFlags.ContainsRest; + transformFlags |= TransformFlags.ContainsRestOrSpread; } break; case SyntaxKind.Decorator: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsDecorators; + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsTypeScriptClassSyntax; break; case SyntaxKind.ObjectLiteralExpression: @@ -3774,7 +3782,7 @@ namespace ts { transformFlags |= TransformFlags.ContainsLexicalThis; } - if (subtreeFlags & TransformFlags.ContainsObjectSpread) { + if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= TransformFlags.AssertESNext; @@ -3785,7 +3793,7 @@ namespace ts { case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.NewExpression: excludeFlags = TransformFlags.ArrayLiteralOrCallOrNewExcludes; - if (subtreeFlags & TransformFlags.ContainsSpread) { + if (subtreeFlags & TransformFlags.ContainsRestOrSpread) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= TransformFlags.AssertES2015; diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index f4a61267144..fbc2dc3f7d2 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -294,7 +294,7 @@ namespace ts { configFileParsingDiagnostics: ReadonlyArray; } - export function getBuilderCreationParameters(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderCreationParameters { + export function getBuilderCreationParameters(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderCreationParameters { let host: BuilderProgramHost; let newProgram: Program; let oldProgram: BuilderProgram; @@ -307,7 +307,14 @@ namespace ts { } else if (isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram as BuilderProgram; - newProgram = createProgram(newProgramOrRootNames, hostOrOptions as CompilerOptions, oldProgramOrHost as CompilerHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions as CompilerOptions, + host: oldProgramOrHost as CompilerHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics, + projectReferences + }); host = oldProgramOrHost as CompilerHost; } else { @@ -623,9 +630,9 @@ namespace ts { * Create the builder to manage semantic diagnostics and cache them */ export function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - export function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray) { - return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + export function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray) { + return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } /** @@ -633,18 +640,18 @@ namespace ts { * to emit the those files and manage semantic diagnostics cache as well */ export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray) { - return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray) { + return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } /** * Creates a builder thats just abstraction over program and can be used with watch */ export function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - export function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - export function createAbstractBuilder(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram { - const { newProgram: program } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics); + export function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; + export function createAbstractBuilder(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram { + const { newProgram: program } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); return { // Only return program, all other methods are not implemented getProgram: () => program, diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index 12936e5b2e8..1689733fac6 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -88,7 +88,7 @@ namespace ts.BuilderState { function getReferencedFileFromImportedModuleSymbol(symbol: Symbol) { if (symbol.declarations && symbol.declarations[0]) { const declarationSourceFile = getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } @@ -100,6 +100,13 @@ namespace ts.BuilderState { return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program: Program, fileName: string, sourceFileDirectory: Path, getCanonicalFileName: GetCanonicalFileName): Path { + return toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } + /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -123,7 +130,7 @@ namespace ts.BuilderState { // Handle triple slash references if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (const referencedFile of sourceFile.referencedFiles) { - const referencedPath = toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + const referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -136,13 +143,44 @@ namespace ts.BuilderState { } const fileName = resolvedTypeReferenceDirective.resolvedFileName!; // TODO: GH#18217 - const typeFilePath = toPath(fileName, sourceFileDirectory, getCanonicalFileName); + const typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + const checker = program.getTypeChecker(); + for (const moduleName of sourceFile.moduleAugmentations) { + if (!isStringLiteral(moduleName)) { continue; } + const symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { continue; } + + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + + // From ambient modules + for (const ambientModule of program.getTypeChecker().getAmbientModules()) { + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } + return referencedFiles; + function addReferenceFromAmbientModule(symbol: Symbol) { + // Add any file other than our own as reference + for (const declaration of symbol.declarations) { + const declarationSourceFile = getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } + function addReferencedFile(referencedPath: Path) { if (!referencedFiles) { referencedFiles = createMap(); diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 51d6478ed1e..f451c91046b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -77,6 +77,7 @@ namespace ts { const allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions); const strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks"); const strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + const strictBindCallApply = getStrictOptionValue(compilerOptions, "strictBindCallApply"); const strictPropertyInitialization = getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); const noImplicitAny = getStrictOptionValue(compilerOptions, "noImplicitAny"); const noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -268,10 +269,6 @@ namespace ts { getFirstIdentifier, ), getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: nodeIn => { - const node = getParseTreeNode(nodeIn, isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, getJsxIntrinsicTagNamesAt, isOptionalParameter: nodeIn => { const node = getParseTreeNode(nodeIn, isParameter); @@ -296,8 +293,8 @@ namespace ts { createPromiseType, createArrayType, getBooleanType: () => booleanType, - getFalseType: () => falseType, - getTrueType: () => trueType, + getFalseType: (fresh?) => fresh ? falseType : regularFalseType, + getTrueType: (fresh?) => fresh ? trueType : regularTrueType, getVoidType: () => voidType, getUndefinedType: () => undefinedType, getNullType: () => nullType, @@ -405,9 +402,22 @@ namespace ts { const nullWideningType = strictNullChecks ? nullType : createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsWideningType, "null"); const stringType = createIntrinsicType(TypeFlags.String, "string"); const numberType = createIntrinsicType(TypeFlags.Number, "number"); - const falseType = createIntrinsicType(TypeFlags.BooleanLiteral, "false"); - const trueType = createIntrinsicType(TypeFlags.BooleanLiteral, "true"); - const booleanType = createBooleanType([falseType, trueType]); + const falseType = createIntrinsicType(TypeFlags.BooleanLiteral, "false") as FreshableIntrinsicType; + const regularFalseType = createIntrinsicType(TypeFlags.BooleanLiteral, "false") as FreshableIntrinsicType; + const trueType = createIntrinsicType(TypeFlags.BooleanLiteral, "true") as FreshableIntrinsicType; + const regularTrueType = createIntrinsicType(TypeFlags.BooleanLiteral, "true") as FreshableIntrinsicType; + falseType.flags |= TypeFlags.FreshLiteral; + trueType.flags |= TypeFlags.FreshLiteral; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + const booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); const esSymbolType = createIntrinsicType(TypeFlags.ESSymbol, "symbol"); const voidType = createIntrinsicType(TypeFlags.Void, "void"); const neverType = createIntrinsicType(TypeFlags.Never, "never"); @@ -446,12 +456,23 @@ namespace ts { const unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); const resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); const silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - const resolvingSignaturesArray = [resolvingSignature]; const enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); const globals = createSymbolTable(); - let amalgamatedDuplicates: Map<{ firstFile: SourceFile, secondFile: SourceFile, firstFileInstances: Map<{ instances: Node[], blockScoped: boolean }>, secondFileInstances: Map<{ instances: Node[], blockScoped: boolean }> }> | undefined; + interface DuplicateInfoForSymbol { + readonly firstFileLocations: Node[]; + readonly secondFileLocations: Node[]; + readonly isBlockScoped: boolean; + } + interface DuplicateInfoForFiles { + readonly firstFile: SourceFile; + readonly secondFile: SourceFile; + /** Key is symbol name. */ + readonly conflictingSymbols: Map; + } + /** Key is "/path/to/a.ts|/path/to/b.ts". */ + let amalgamatedDuplicates: Map | undefined; const reverseMappedCache = createMap(); let ambientModulesCache: Symbol[] | undefined; /** @@ -463,6 +484,8 @@ namespace ts { let globalObjectType: ObjectType; let globalFunctionType: ObjectType; + let globalCallableFunctionType: ObjectType; + let globalNewableFunctionType: ObjectType; let globalArrayType: GenericType; let globalReadonlyArrayType: GenericType; let globalStringType: ObjectType; @@ -482,6 +505,7 @@ namespace ts { let deferredGlobalESSymbolType: ObjectType; let deferredGlobalTypedPropertyDescriptorType: GenericType; let deferredGlobalPromiseType: GenericType; + let deferredGlobalPromiseLikeType: GenericType; let deferredGlobalPromiseConstructorSymbol: Symbol | undefined; let deferredGlobalPromiseConstructorLikeType: ObjectType; let deferredGlobalIterableType: GenericType; @@ -494,7 +518,6 @@ namespace ts { let deferredGlobalImportMetaType: ObjectType; let deferredGlobalExtractSymbol: Symbol; - let deferredNodes: Map | undefined; const allPotentiallyUnusedIdentifiers = createMap(); // key is file name let flowLoopStart = 0; @@ -588,6 +611,8 @@ namespace ts { FunctionFacts = FunctionStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, UndefinedFacts = TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | EQUndefined | EQUndefinedOrNull | NENull | Falsy, NullFacts = TypeofEQObject | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEFunction | TypeofNEHostObject | EQNull | EQUndefinedOrNull | NEUndefined | Falsy, + EmptyObjectStrictFacts = All & ~(EQUndefined | EQNull | EQUndefinedOrNull), + EmptyObjectFacts = All, } const typeofEQFacts = createMapFromTemplate({ @@ -627,7 +652,7 @@ namespace ts { const identityRelation = createMap(); const enumRelation = createMap(); - type TypeSystemEntity = Symbol | Type | Signature; + type TypeSystemEntity = Node | Symbol | Type | Signature; const enum TypeSystemPropertyName { Type, @@ -635,6 +660,8 @@ namespace ts { DeclaredType, ResolvedReturnType, ImmediateBaseConstraint, + EnumTagType, + JSDocTypeReference, } const enum CheckMode { @@ -824,7 +851,7 @@ namespace ts { */ function mergeSymbol(target: Symbol, source: Symbol): Symbol { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & SymbolFlags.JSContainer) { + (source.flags | target.flags) & SymbolFlags.Assignment) { Debug.assert(source !== target); if (!(target.flags & SymbolFlags.Transient)) { target = cloneSymbol(target); @@ -837,7 +864,7 @@ namespace ts { target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - isAssignmentDeclaration(target.valueDeclaration) || + isAssignmentDeclaration(target.valueDeclaration) && !isAssignmentDeclaration(source.valueDeclaration) || isEffectiveModuleDeclaration(target.valueDeclaration) && !isEffectiveModuleDeclaration(source.valueDeclaration))) { // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; @@ -866,50 +893,45 @@ namespace ts { : Diagnostics.Duplicate_identifier_0; const sourceSymbolFile = source.declarations && getSourceFileOfNode(source.declarations[0]); const targetSymbolFile = target.declarations && getSourceFileOfNode(target.declarations[0]); + const symbolName = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { const firstFile = comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === Comparison.LessThan ? sourceSymbolFile : targetSymbolFile; const secondFile = firstFile === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; - const cacheKey = `${firstFile.path}|${secondFile.path}`; - const existing = amalgamatedDuplicates.get(cacheKey) || { firstFile, secondFile, firstFileInstances: createMap(), secondFileInstances: createMap() }; - const symbolName = symbolToString(source); - const firstInstanceList = existing.firstFileInstances.get(symbolName) || { instances: [], blockScoped: isEitherBlockScoped }; - const secondInstanceList = existing.secondFileInstances.get(symbolName) || { instances: [], blockScoped: isEitherBlockScoped }; - - forEach(source.declarations, node => { - const errorNode = (getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? getOuterNameOfJsInitializer(node) : getNameOfDeclaration(node)) || node; - const targetList = sourceSymbolFile === firstFile ? firstInstanceList : secondInstanceList; - targetList.instances.push(errorNode); - }); - forEach(target.declarations, node => { - const errorNode = (getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? getOuterNameOfJsInitializer(node) : getNameOfDeclaration(node)) || node; - const targetList = targetSymbolFile === firstFile ? firstInstanceList : secondInstanceList; - targetList.instances.push(errorNode); - }); - - existing.firstFileInstances.set(symbolName, firstInstanceList); - existing.secondFileInstances.set(symbolName, secondInstanceList); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + const filesDuplicates = getOrUpdate(amalgamatedDuplicates, `${firstFile.path}|${secondFile.path}`, () => + ({ firstFile, secondFile, conflictingSymbols: createMap() })); + const conflictingSymbolInfo = getOrUpdate(filesDuplicates.conflictingSymbols, symbolName, () => + ({ isBlockScoped: isEitherBlockScoped, firstFileLocations: [], secondFileLocations: [] })); + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source); } - const symbolName = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source); } return target; + + function addDuplicateLocations(locs: Node[], symbol: Symbol): void { + for (const decl of symbol.declarations) { + pushIfUnique(locs, (getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? getNameOfExpando(decl) : getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target: Symbol, message: DiagnosticMessage, symbolName: string, source: Symbol) { forEach(target.declarations, node => { - const errorNode = (getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? getOuterNameOfJsInitializer(node) : getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + const errorNode = (getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode: Node, message: DiagnosticMessage, symbolName: string, relatedNode: Node | undefined) { + function addDuplicateDeclarationError(errorNode: Node, message: DiagnosticMessage, symbolName: string, relatedNodes: ReadonlyArray | undefined) { const err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && length(err.relatedInformation) < 5) { + for (const relatedNode of relatedNodes || emptyArray) { + err.relatedInformation = err.relatedInformation || []; + if (length(err.relatedInformation) >= 5) continue; addRelatedInfo(err, !length(err.relatedInformation) ? createDiagnosticForNode(relatedNode, Diagnostics._0_was_also_declared_here, symbolName) : createDiagnosticForNode(relatedNode, Diagnostics.and_here)); } } @@ -1211,17 +1233,25 @@ namespace ts { // local types not visible outside the function body : false; } - if (meaning & SymbolFlags.Value && result.flags & SymbolFlags.FunctionScopedVariable) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === SyntaxKind.Parameter || - ( - lastLocation === (location).type && - !!findAncestor(result.valueDeclaration, isParameter) - ); + if (meaning & result.flags & SymbolFlags.Variable) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + const functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= ScriptTarget.ES2015 && isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & SymbolFlags.FunctionScopedVariable) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === SyntaxKind.Parameter || + ( + lastLocation === (location).type && + !!findAncestor(result.valueDeclaration, isParameter) + ); + } } } else if (location.kind === SyntaxKind.ConditionalType) { @@ -1312,7 +1342,10 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location as ClassLikeDeclaration | InterfaceDeclaration)), name, meaning & SymbolFlags.Type)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location as ClassLikeDeclaration | InterfaceDeclaration).members || emptySymbols, name, meaning & SymbolFlags.Type)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -1436,7 +1469,7 @@ namespace ts { if (!result) { if (lastLocation) { Debug.assert(lastLocation.kind === SyntaxKind.SourceFile); - if ((lastLocation as SourceFile).commonJsModuleIndicator && name === "exports") { + if ((lastLocation as SourceFile).commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -1446,7 +1479,7 @@ namespace ts { } } if (!result) { - if (originalLocation && isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && isInJSFile(originalLocation) && originalLocation.parent) { if (isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -1622,7 +1655,7 @@ namespace ts { } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation: Node, name: __String, meaning: SymbolFlags): boolean { - const namespaceMeaning = SymbolFlags.Namespace | (isInJavaScriptFile(errorLocation) ? SymbolFlags.Value : 0); + const namespaceMeaning = SymbolFlags.Namespace | (isInJSFile(errorLocation) ? SymbolFlags.Value : 0); if (meaning === namespaceMeaning) { const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~namespaceMeaning, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false)); const parent = errorLocation.parent; @@ -1657,7 +1690,10 @@ namespace ts { } const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & SymbolFlags.NamespaceModule)) { - error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, unescapeLeadingUnderscores(name)); + const message = (name === "Promise" || name === "Symbol") + ? Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, unescapeLeadingUnderscores(name)); return true; } } @@ -1685,7 +1721,9 @@ namespace ts { function checkResolvedBlockScopedVariable(result: Symbol, errorLocation: Node): void { Debug.assert(!!(result.flags & SymbolFlags.BlockScopedVariable || result.flags & SymbolFlags.Class || result.flags & SymbolFlags.Enum)); // Block-scoped variables cannot be used before their definition - const declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) || isClassLike(d) || (d.kind === SyntaxKind.EnumDeclaration) ? d : undefined); + const declaration = find( + result.declarations, + d => isBlockOrCatchScoped(d) || isClassLike(d) || (d.kind === SyntaxKind.EnumDeclaration) || isInJSFile(d) && !!getJSDocEnumTag(d)); if (declaration === undefined) return Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); @@ -1785,7 +1823,7 @@ namespace ts { return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!isSourceFileJavaScript(file)) { + if (!isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -1900,7 +1938,7 @@ namespace ts { combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - const moduleName = getFullyQualifiedName(moduleSymbol); + const moduleName = getFullyQualifiedName(moduleSymbol, node); const declarationName = declarationNameToString(name); const suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -1976,7 +2014,7 @@ namespace ts { */ function isNonLocalAlias(symbol: Symbol | undefined, excludes = SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace): symbol is Symbol { if (!symbol) return false; - return (symbol.flags & (SymbolFlags.Alias | excludes)) === SymbolFlags.Alias || !!(symbol.flags & SymbolFlags.Alias && symbol.flags & SymbolFlags.JSContainer); + return (symbol.flags & (SymbolFlags.Alias | excludes)) === SymbolFlags.Alias || !!(symbol.flags & SymbolFlags.Alias && symbol.flags & SymbolFlags.Assignment); } function resolveSymbol(symbol: Symbol, dontResolveAlias?: boolean): Symbol; @@ -2066,8 +2104,8 @@ namespace ts { } } - function getFullyQualifiedName(symbol: Symbol): string { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol: Symbol, containingLocation?: Node): string { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, SymbolFormatFlags.DoNotIncludeSymbolChain | SymbolFormatFlags.AllowAnyNodeKind); } /** @@ -2078,11 +2116,11 @@ namespace ts { return undefined; } - const namespaceMeaning = SymbolFlags.Namespace | (isInJavaScriptFile(name) ? meaning & SymbolFlags.Value : 0); + const namespaceMeaning = SymbolFlags.Namespace | (isInJSFile(name) ? meaning & SymbolFlags.Value : 0); let symbol: Symbol | undefined; if (name.kind === SyntaxKind.Identifier) { - const message = meaning === namespaceMeaning ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0; - const symbolFromJSPrototype = isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + const message = meaning === namespaceMeaning ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + const symbolFromJSPrototype = isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -2098,7 +2136,7 @@ namespace ts { else if (namespace === unknownSymbol) { return namespace; } - if (isInJavaScriptFile(name)) { + if (isInJSFile(name)) { if (namespace.valueDeclaration && isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -2134,16 +2172,16 @@ namespace ts { * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name: Identifier, meaning: SymbolFlags) { + function resolveEntityNameFromAssignmentDeclaration(name: Identifier, meaning: SymbolFlags) { if (isJSDocTypeReference(name.parent)) { - const secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + const secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node: TypeReferenceNode): Node | undefined { + function getAssignmentDeclarationLocation(node: TypeReferenceNode): Node | undefined { const typeAlias = findAncestor(node, node => !(isJSDocNode(node) || node.flags & NodeFlags.JSDoc) ? "quit" : isJSDocTypeAlias(node)); if (typeAlias) { return; @@ -2151,7 +2189,7 @@ namespace ts { const host = getJSDocHost(node); if (isExpressionStatement(host) && isBinaryExpression(host.expression) && - getSpecialPropertyAssignmentKind(host.expression) === SpecialPropertyAssignmentKind.PrototypeProperty) { + getAssignmentDeclarationKind(host.expression) === AssignmentDeclarationKind.PrototypeProperty) { // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration const symbol = getSymbolOfNode(host.expression.left); if (symbol) { @@ -2160,7 +2198,7 @@ namespace ts { } if ((isObjectLiteralMethod(host) || isPropertyAssignment(host)) && isBinaryExpression(host.parent.parent) && - getSpecialPropertyAssignmentKind(host.parent.parent) === SpecialPropertyAssignmentKind.Prototype) { + getAssignmentDeclarationKind(host.parent.parent) === AssignmentDeclarationKind.Prototype) { // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration const symbol = getSymbolOfNode(host.parent.parent.left); if (symbol) { @@ -2176,8 +2214,8 @@ namespace ts { function getDeclarationOfJSPrototypeContainer(symbol: Symbol) { const decl = symbol.parent!.valueDeclaration; - const initializer = isAssignmentDeclaration(decl) ? getAssignedJavascriptInitializer(decl) : - hasOnlyExpressionInitializer(decl) ? getDeclaredJavascriptInitializer(decl) : + const initializer = isAssignmentDeclaration(decl) ? getAssignedExpandoInitializer(decl) : + hasOnlyExpressionInitializer(decl) ? getDeclaredExpandoInitializer(decl) : undefined; return initializer || decl; } @@ -2213,7 +2251,7 @@ namespace ts { const sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -2234,7 +2272,7 @@ namespace ts { } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { const diag = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -2267,7 +2305,7 @@ namespace ts { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - const tsExtension = tryExtractTypeScriptExtension(moduleReference); + const tsExtension = tryExtractTSExtension(moduleReference); if (tsExtension) { const diag = Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, removeExtension(moduleReference, tsExtension)); @@ -2292,12 +2330,12 @@ namespace ts { ? chainDiagnosticMessages( /*details*/ undefined, Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, - packageId.name, getMangledNameForScopedPackage(packageId.name)) + packageId.name, mangleScopedPackageName(packageId.name)) : chainDiagnosticMessages( /*details*/ undefined, Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, - getMangledNameForScopedPackage(packageId.name)) + mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, chainDiagnosticMessages( errorInfo, @@ -2316,7 +2354,7 @@ namespace ts { } function getCommonJsExportEquals(exported: Symbol | undefined, moduleSymbol: Symbol): Symbol | undefined { - if (!exported || moduleSymbol.exports!.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports!.size === 1) { return exported; } const merged = cloneSymbol(exported); @@ -3050,6 +3088,9 @@ namespace ts { if (flags & SymbolFormatFlags.UseAliasDefinedOutsideCurrentScope) { nodeFlags |= NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope; } + if (flags & SymbolFormatFlags.DoNotIncludeSymbolChain) { + nodeFlags |= NodeBuilderFlags.DoNotIncludeSymbolChain; + } const builder = flags & SymbolFormatFlags.AllowAnyNodeKind ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); @@ -3127,7 +3168,12 @@ namespace ts { const context: NodeBuilderContext = { enclosingDeclaration, flags: flags || NodeBuilderFlags.None, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: noop, moduleResolverHost: flags! & NodeBuilderFlags.DoNotIncludeSymbolChain ? { + getCommonSourceDirectory: (host as Program).getCommonSourceDirectory ? () => (host as Program).getCommonSourceDirectory() : () => "", + getSourceFiles: () => host.getSourceFiles(), + getCurrentDirectory: host.getCurrentDirectory && (() => host.getCurrentDirectory!()) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -3280,6 +3326,9 @@ namespace ts { } if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { const types = type.flags & TypeFlags.Union ? formatUnionTypes((type).types) : (type).types; + if (length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } const typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { const unionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode(type.flags & TypeFlags.Union ? SyntaxKind.UnionType : SyntaxKind.IntersectionType, typeNodes); @@ -3352,7 +3401,7 @@ namespace ts { if (symbol) { const isConstructorObject = getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & SymbolFlags.Class; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. const isInstanceType = type === getInferredClassType(symbol) ? SymbolFlags.Type : SymbolFlags.Value; return symbolToTypeNode(symbol, context, isInstanceType); @@ -3458,8 +3507,8 @@ namespace ts { const arity = getTypeReferenceArity(type); const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); const hasRestElement = (type.target).hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (let i = (type.target).minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (let i = (type.target).minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? createRestTypeNode(createArrayTypeNode(tupleConstituentNodes[i])) : createOptionalTypeNode(tupleConstituentNodes[i]); @@ -3854,7 +3903,7 @@ namespace ts { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. let chain: Symbol[]; const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & NodeBuilderFlags.UseFullyQualifiedType) && !(context.flags & NodeBuilderFlags.DoNotIncludeSymbolChain)) { chain = Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); Debug.assert(chain && chain.length > 0); } @@ -4109,6 +4158,9 @@ namespace ts { function createExpressionFromSymbolChain(chain: Symbol[], index: number): Expression { const typeParameterNodes = lookupTypeParameterNodes(chain, index, context); const symbol = chain[index]; + if (some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= NodeBuilderFlags.InInitialEntityName; @@ -4174,7 +4226,7 @@ namespace ts { const baseType = t.flags & TypeFlags.BooleanLiteral ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & TypeFlags.Union) { const count = (baseType).types.length; - if (i + count <= types.length && types[i + count - 1] === (baseType).types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType((baseType).types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -4463,6 +4515,8 @@ namespace ts { switch (propertyName) { case TypeSystemPropertyName.Type: return !!getSymbolLinks(target).type; + case TypeSystemPropertyName.EnumTagType: + return !!(getNodeLinks(target as JSDocEnumTag).resolvedEnumType); case TypeSystemPropertyName.DeclaredType: return !!getSymbolLinks(target).declaredType; case TypeSystemPropertyName.ResolvedBaseConstructorType: @@ -4471,6 +4525,8 @@ namespace ts { return !!(target).resolvedReturnType; case TypeSystemPropertyName.ImmediateBaseConstraint: return !!(target).immediateBaseConstraint; + case TypeSystemPropertyName.JSDocTypeReference: + return !!getSymbolLinks(target as Symbol).resolvedJSDocType; } return Debug.assertNever(propertyName); } @@ -4648,17 +4704,17 @@ namespace ts { const elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); const index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, t => sliceTupleType(t, index)) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array const index = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? + type = everyType(parentType, isTupleLikeType) ? getTupleElementType(parentType, index) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { @@ -4674,11 +4730,11 @@ namespace ts { } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & TypeFlags.Undefined)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & TypeFlags.Undefined)) { type = getTypeWithFacts(type, TypeFacts.NEUndefined); } return declaration.initializer && !getEffectiveTypeAnnotationNode(walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], UnionReduction.Subtype) : + getUnionType([type, checkDeclarationInitializer(declaration)], UnionReduction.Subtype) : type; } @@ -4736,7 +4792,7 @@ namespace ts { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || isInJavaScriptFile(declaration)) && + if ((noImplicitAny || isInJSFile(declaration)) && declaration.kind === SyntaxKind.VariableDeclaration && !isBindingPattern(declaration.name) && !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -4768,7 +4824,7 @@ namespace ts { return getReturnTypeOfSignature(getterSignature); } } - if (isInJavaScriptFile(declaration)) { + if (isInJSFile(declaration)) { const typeTag = getJSDocType(func); if (typeTag && isFunctionTypeNode(typeTag)) { return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); @@ -4780,10 +4836,10 @@ namespace ts { return addOptionality(type, isOptional); } } - else if (isInJavaScriptFile(declaration)) { - const expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (isInJSFile(declaration)) { + const containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } @@ -4808,16 +4864,16 @@ namespace ts { return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol: Symbol, resolvedSymbol?: Symbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - const specialDeclaration = getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - const tag = getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol: Symbol, resolvedSymbol?: Symbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + const container = getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + const tag = getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - const expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + const containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } let definedInConstructor = false; let definedInMethod = false; @@ -4831,8 +4887,8 @@ namespace ts { return errorType; } - const special = isPropertyAccessExpression(expression) ? getSpecialPropertyAccessKind(expression) : getSpecialPropertyAssignmentKind(expression); - if (special === SpecialPropertyAssignmentKind.ThisProperty) { + const kind = isPropertyAccessExpression(expression) ? getAssignmentDeclarationPropertyAccessKind(expression) : getAssignmentDeclarationKind(expression); + if (kind === AssignmentDeclarationKind.ThisProperty) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -4840,9 +4896,9 @@ namespace ts { definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } let type = jsdocType; @@ -4850,7 +4906,7 @@ namespace ts { let constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types!, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - const propType = getTypeOfSpecialPropertyOfBaseType(symbol); + const propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -4861,16 +4917,14 @@ namespace ts { } const widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, t => !!(t.flags & ~TypeFlags.Nullable)) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl: Node, symbol: Symbol, init: Expression | undefined): Type | undefined { - if (!isInJavaScriptFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl: Node, symbol: Symbol, init: Expression | undefined): Type | undefined { + if (!isInJSFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) { return undefined; } const exports = createSymbolTable(); @@ -4890,7 +4944,7 @@ namespace ts { return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType: Type | undefined, expression: Expression, _symbol: Symbol, declaration: Declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType: Type | undefined, expression: Expression, _symbol: Symbol, declaration: Declaration) { const typeNode = getJSDocType(expression.parent); if (typeNode) { const type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -4905,10 +4959,10 @@ namespace ts { } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol: Symbol, resolvedSymbol: Symbol | undefined, expression: BinaryExpression, special: SpecialPropertyAssignmentKind) { + function getInitializerTypeFromAssignmentDeclaration(symbol: Symbol, resolvedSymbol: Symbol | undefined, expression: BinaryExpression, kind: AssignmentDeclarationKind) { const type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & TypeFlags.Object && - special === SpecialPropertyAssignmentKind.ModuleExports && + kind === AssignmentDeclarationKind.ModuleExports && symbol.escapedName === InternalSymbolName.ExportEquals) { const exportedType = resolveStructuredTypeMembers(type as ObjectType); const members = createSymbolTable(); @@ -4938,9 +4992,7 @@ namespace ts { return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -4966,8 +5018,8 @@ namespace ts { } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty: Symbol) { - const parentDeclaration = forEach(specialProperty.declarations, d => { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property: Symbol) { + const parentDeclaration = forEach(property.declarations, d => { const parent = getThisContainer(d, /*includeArrowFunctions*/ false).parent; return isClassLike(parent) && parent; }); @@ -4975,7 +5027,7 @@ namespace ts { const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)) as InterfaceType; const baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -4990,8 +5042,8 @@ namespace ts { if (isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -5091,9 +5143,9 @@ namespace ts { type = isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -5150,7 +5202,7 @@ namespace ts { return type; } if (declaration.kind === SyntaxKind.ExportAssignment) { - return checkExpression((declaration).expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached((declaration).expression), declaration); } // Handle variable, parameter or property @@ -5158,9 +5210,9 @@ namespace ts { return errorType; } let type: Type | undefined; - if (isInJavaScriptFile(declaration) && + if (isInJSFile(declaration) && (isBinaryExpression(declaration) || isPropertyAccessExpression(declaration) && isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (isJSDocPropertyLikeTag(declaration) || isPropertyAccessExpression(declaration) @@ -5174,7 +5226,7 @@ namespace ts { return getTypeOfFuncClassEnumModule(symbol); } type = isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (isPropertyAssignment(declaration)) { @@ -5243,7 +5295,7 @@ namespace ts { const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); - if (getter && isInJavaScriptFile(getter)) { + if (getter && isInJSFile(getter)) { const jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -5274,14 +5326,12 @@ namespace ts { } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter!, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -5306,7 +5356,7 @@ namespace ts { let links = getSymbolLinks(symbol); const originalLinks = links; if (!links.type) { - const jsDeclaration = getDeclarationOfJSInitializer(symbol.valueDeclaration); + const jsDeclaration = getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { const jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (hasEntries(jsSymbol.exports) || hasEntries(jsSymbol.members))) { @@ -5335,7 +5385,7 @@ namespace ts { } else if (declaration.kind === SyntaxKind.BinaryExpression || declaration.kind === SyntaxKind.PropertyAccessExpression && declaration.parent.kind === SyntaxKind.BinaryExpression) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & SymbolFlags.ValueModule && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) { const resolvedModule = resolveExternalModuleSymbol(symbol); @@ -5344,7 +5394,7 @@ namespace ts { return errorType; } const exportEquals = getMergedSymbol(symbol.exports!.get(InternalSymbolName.ExportEquals)!); - const type = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + const type = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } @@ -5564,7 +5614,7 @@ namespace ts { const constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type: InterfaceType): ExpressionWithTypeArguments | undefined { @@ -5573,10 +5623,7 @@ namespace ts { function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { const typeArgCount = length(typeArgumentNodes); - const isJavascript = isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, SignatureKind.Call); - } + const isJavascript = isInJSFile(location); return filter(getSignaturesOfType(type, SignatureKind.Construct), sig => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); } @@ -5584,7 +5631,7 @@ namespace ts { function getInstantiatedConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { const signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); - return sameMap(signatures, sig => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJavaScriptFile(location)) : sig); + return sameMap(signatures, sig => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJSFile(location)) : sig); } /** @@ -5658,7 +5705,9 @@ namespace ts { const baseTypeNode = getBaseTypeNodeOfClass(type)!; const typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); let baseType: Type; - const originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + const originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & SymbolFlags.Class && areAllOuterTypeParametersApplied(originalBaseType!)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -5669,8 +5718,8 @@ namespace ts { else if (baseConstructorType.flags & TypeFlags.Any) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -6161,7 +6210,7 @@ namespace ts { if (type.flags & TypeFlags.UniqueESSymbol) { return `__@${type.symbol.escapedName}@${getSymbolId(type.symbol)}` as __String; } - if (type.flags & TypeFlags.StringOrNumberLiteral) { + if (type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { return escapeLeadingUnderscores("" + (type).value); } return Debug.fail(); @@ -6460,7 +6509,7 @@ namespace ts { return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } const baseTypeNode = getBaseTypeNodeOfClass(classType)!; - const isJavaScript = isInJavaScriptFile(baseTypeNode); + const isJavaScript = isInJSFile(baseTypeNode); const typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); const typeArgCount = length(typeArguments); const result: Signature[] = []; @@ -6682,6 +6731,7 @@ namespace ts { // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = filter(type.callSignatures, sig => isJSConstructor(sig.declaration)); } // And likewise for construct signatures for classes if (symbol.flags & SymbolFlags.Class) { @@ -6796,7 +6846,7 @@ namespace ts { function getConstraintTypeFromMappedType(type: MappedType) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type: MappedType) { @@ -6942,8 +6992,9 @@ namespace ts { getPropertiesOfObjectType(type); } - function isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression): boolean { - return obj.properties.some(property => { + function isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes): boolean { + const list = obj.properties as NodeArray; + return list.some(property => { const name = property.name && getTextOfPropertyName(property.name); const expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); @@ -7277,10 +7328,10 @@ namespace ts { } } else if (isUnion) { - const index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, IndexKind.Number)) || getIndexInfoOfType(type, IndexKind.String)); - if (index) { - checkFlags |= index.isReadonly ? CheckFlags.Readonly : 0; - indexTypes = append(indexTypes, index.type); + const indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, IndexKind.Number) || getIndexInfoOfType(type, IndexKind.String)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? CheckFlags.Readonly : 0; + indexTypes = append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= CheckFlags.Partial; @@ -7373,8 +7424,12 @@ namespace ts { if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - const symbol = getPropertyOfObjectType(globalFunctionType, name); + const functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + const symbol = getPropertyOfObjectType(functionType, name); if (symbol) { return symbol; } @@ -7463,7 +7518,7 @@ namespace ts { } function isJSDocOptionalParameter(node: ParameterDeclaration) { - return isInJavaScriptFile(node) && ( + return isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === SyntaxKind.JSDocOptionalType || getJSDocParameterTags(node).some(({ isBracketed, typeExpression }) => @@ -7582,7 +7637,7 @@ namespace ts { const iife = getImmediatelyInvokedFunctionExpression(declaration); const isJSConstructSignature = isJSDocConstructSignature(declaration); const isUntypedSignatureInJSFile = !iife && - isInJavaScriptFile(declaration) && + isInJSFile(declaration) && isValueSignatureDeclaration(declaration) && !hasJSDocParameterTags(declaration) && !getJSDocType(declaration); @@ -7638,7 +7693,7 @@ namespace ts { getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)) : undefined; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - const hasRestLikeParameter = hasRestParameter(declaration) || isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + const hasRestLikeParameter = hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); @@ -7672,7 +7727,7 @@ namespace ts { } function getSignatureOfTypeTag(node: SignatureDeclaration | JSDocSignature) { - const typeTag = isInJavaScriptFile(node) ? getJSDocTypeTag(node) : undefined; + const typeTag = isInJSFile(node) ? getJSDocTypeTag(node) : undefined; const signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -7767,7 +7822,7 @@ namespace ts { else { const type = signature.declaration && getEffectiveReturnTypeNode(signature.declaration); let jsdocPredicate: TypePredicate | undefined; - if (!type && isInJavaScriptFile(signature.declaration)) { + if (!type && isInJSFile(signature.declaration)) { const jsdocSignature = getSignatureOfTypeTag(signature.declaration!); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -7814,6 +7869,7 @@ namespace ts { let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper!) : signature.unionSignatures ? getUnionType(map(signature.unionSignatures, getReturnTypeOfSignature), UnionReduction.Subtype) : getReturnTypeFromAnnotation(signature.declaration!) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration!)) || (nodeIsMissing((signature.declaration).body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -7851,7 +7907,7 @@ namespace ts { return getTypeFromTypeNode(typeNode); } if (declaration.kind === SyntaxKind.GetAccessor && !hasNonBindableDynamicName(declaration)) { - const jsDocType = isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + const jsDocType = isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -7928,7 +7984,7 @@ namespace ts { return getSignatureInstantiation( signature, map(signature.typeParameters, tp => tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp), - isInJavaScriptFile(signature.declaration)); + isInJSFile(signature.declaration)); } function getBaseSignature(signature: Signature) { @@ -8138,10 +8194,10 @@ namespace ts { if (typeParameters) { const numTypeArguments = length(node.typeArguments); const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - const isJs = isInJavaScriptFile(node); + const isJs = isInJSFile(node); const isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - const missingAugmentsTag = isJs && node.parent.kind !== SyntaxKind.JSDocAugmentsTag; + const missingAugmentsTag = isJs && isExpressionWithTypeArguments(node) && !isJSDocAugmentsTag(node.parent); const diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -8172,7 +8228,7 @@ namespace ts { const id = getTypeListId(typeArguments); let instantiation = links.instantiations!.get(id); if (!instantiation) { - links.instantiations!.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations!.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -8239,10 +8295,19 @@ namespace ts { return type; } - // JS are 'string' or 'number', not an enum type. - const enumTag = symbol.valueDeclaration && getJSDocEnumTag(symbol.valueDeclaration); + // JS enums are 'string' or 'number', not an enum type. + const enumTag = isInJSFile(node) && symbol.valueDeclaration && getJSDocEnumTag(symbol.valueDeclaration); if (enumTag) { - return enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + const links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, TypeSystemPropertyName.EnumTagType)) { + return errorType; + } + let type = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type = errorType; + error(node, Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type); } // Get type from reference to named type that cannot be generic (enum or type parameter) @@ -8273,12 +8338,21 @@ namespace ts { * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node: NodeWithTypeArguments, symbol: Symbol, typeArguments: Type[] | undefined): Type | undefined { + if (!pushTypeResolution(symbol, TypeSystemPropertyName.JSDocTypeReference)) { + return errorType; + } const assignedType = getAssignedClassType(symbol); const valueType = getTypeOfSymbol(symbol); const referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType)!; + const type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType)!; + return getSymbolLinks(symbol).resolvedJSDocType = type; } } @@ -8415,7 +8489,7 @@ namespace ts { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -8512,6 +8586,10 @@ namespace ts { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise" as __String, /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors: boolean) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike" as __String, /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors: boolean): Symbol | undefined { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise" as __String, reportErrors)); } @@ -8678,6 +8756,20 @@ namespace ts { return links.resolvedType; } + function sliceTupleType(type: TupleTypeReference, index: number) { + const tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType( + (type.typeArguments || emptyArray).slice(index), + Math.max(0, tuple.minLength - index), + tuple.hasRestElement, + tuple.associatedNames && tuple.associatedNames.slice(index), + ); + } + function getTypeFromOptionalTypeNode(node: OptionalTypeNode): Type { const type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -8814,7 +8906,7 @@ namespace ts { t.flags & TypeFlags.StringLiteral && includes & TypeFlags.String || t.flags & TypeFlags.NumberLiteral && includes & TypeFlags.Number || t.flags & TypeFlags.UniqueESSymbol && includes & TypeFlags.ESSymbol || - t.flags & TypeFlags.StringOrNumberLiteral && t.flags & TypeFlags.FreshLiteral && containsType(types, (t).regularType); + t.flags & TypeFlags.Literal && t.flags & TypeFlags.FreshLiteral && containsType(types, (t).regularType); if (remove) { orderedRemoveItemAt(types, i); } @@ -8842,7 +8934,7 @@ namespace ts { } switch (unionReduction) { case UnionReduction.Literal: - if (includes & TypeFlags.StringOrNumberLiteralOrUnique) { + if (includes & TypeFlags.StringOrNumberLiteralOrUnique | TypeFlags.BooleanLiteral) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -9244,13 +9336,16 @@ namespace ts { } } const propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && getAssignmentTargetKind(accessExpression) !== AssignmentKind.Definite ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - const restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, t => !(t).target.hasRestElement)) { + const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, t => getRestTypeOfTupleType(t) || undefinedType); } } if (!(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike)) { @@ -9343,12 +9438,24 @@ namespace ts { // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. const objectType = getSimplifiedType(type.objectType); const indexType = getSimplifiedType(type.indexType); - if (objectType.flags & TypeFlags.Union) { - return type.simplified = mapType(objectType, t => getSimplifiedType(getIndexedAccessType(t, indexType))); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & TypeFlags.Union) { + return type.simplified = mapType(indexType, t => getSimplifiedType(getIndexedAccessType(objectType, t))); } - if (objectType.flags & TypeFlags.Intersection) { - return type.simplified = getIntersectionType(map((objectType as IntersectionType).types, t => getSimplifiedType(getIndexedAccessType(t, indexType)))); + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & TypeFlags.Instantiable)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & TypeFlags.Union) { + return type.simplified = mapType(objectType, t => getSimplifiedType(getIndexedAccessType(t, indexType))); + } + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & TypeFlags.Intersection) { + return type.simplified = getIntersectionType(map((objectType as IntersectionType).types, t => getSimplifiedType(getIndexedAccessType(t, indexType)))); + } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] + // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -9814,8 +9921,8 @@ namespace ts { } function getFreshTypeOfLiteralType(type: Type): Type { - if (type.flags & TypeFlags.StringOrNumberLiteral && !(type.flags & TypeFlags.FreshLiteral)) { - if (!(type).freshType) { + if (type.flags & TypeFlags.Literal && !(type.flags & TypeFlags.FreshLiteral)) { + if (!(type).freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already const freshType = createLiteralType(type.flags | TypeFlags.FreshLiteral, (type).value, (type).symbol); freshType.regularType = type; (type).freshType = freshType; @@ -9826,7 +9933,7 @@ namespace ts { } function getRegularTypeOfLiteralType(type: Type): Type { - return type.flags & TypeFlags.StringOrNumberLiteral && type.flags & TypeFlags.FreshLiteral ? (type).regularType : + return type.flags & TypeFlags.Literal && type.flags & TypeFlags.FreshLiteral ? (type).regularType : type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getRegularTypeOfLiteralType)) : type; } @@ -10167,7 +10274,7 @@ namespace ts { // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. let declaration = symbol.declarations[0]; - if (isInJavaScriptFile(declaration)) { + if (isInJSFile(declaration)) { const paramTag = findAncestor(declaration, isJSDocParameterTag); if (paramTag) { const paramSymbol = getParameterSymbolFromJSDoc(paramTag); @@ -10177,7 +10284,7 @@ namespace ts { } } let outerTypeParameters = getOuterTypeParameters(declaration, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration)) { + if (isJSConstructor(declaration)) { const templateTagParameters = getTypeParametersFromDeclaration(declaration as DeclarationWithTypeParameters); outerTypeParameters = addRange(outerTypeParameters, templateTagParameters); } @@ -10265,7 +10372,15 @@ namespace ts { if (typeVariable) { const mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(mappedTypeVariable, t => { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; + } + type.instantiating = true; + const result = mapType(mappedTypeVariable, t => { if (t.flags & (TypeFlags.AnyOrUnknown | TypeFlags.InstantiableNonPrimitive | TypeFlags.Object | TypeFlags.Intersection) && t !== wildcardType) { const replacementMapper = createReplacementMapper(typeVariable, t, mapper); return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : @@ -10275,6 +10390,8 @@ namespace ts { } return t; }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); @@ -10304,6 +10421,12 @@ namespace ts { const result = createObjectType(type.objectFlags | ObjectFlags.Instantiated, type.symbol); if (type.objectFlags & ObjectFlags.Mapped) { (result).declaration = (type).declaration; + // C.f. instantiateSignature + const origTypeParameter = getTypeParameterFromMappedType(type); + const freshTypeParameter = cloneTypeParameter(origTypeParameter); + (result).typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -10423,7 +10546,7 @@ namespace ts { // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. - function isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike): boolean { + function isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike | JsxChild): boolean { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); switch (node.kind) { case SyntaxKind.FunctionExpression: @@ -10445,7 +10568,7 @@ namespace ts { case SyntaxKind.ParenthesizedExpression: return isContextSensitive((node).expression); case SyntaxKind.JsxAttributes: - return some((node).properties, isContextSensitive); + return some((node).properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive); case SyntaxKind.JsxAttribute: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. const { initializer } = node as JsxAttribute; @@ -10488,7 +10611,7 @@ namespace ts { } function isContextSensitiveFunctionOrObjectLiteralMethod(func: Node): func is FunctionExpression | ArrowFunction | MethodDeclaration { - return (isInJavaScriptFile(func) && isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) && + return (isInJSFile(func) && isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } @@ -10544,7 +10667,8 @@ namespace ts { return source.flags & TypeFlags.Union ? every((source).types, t => isTypeDerivedFrom(t, target)) : target.flags & TypeFlags.Union ? some((target).types, t => isTypeDerivedFrom(source, t)) : source.flags & TypeFlags.InstantiableNonPrimitive ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : + target === globalObjectType ? !!(source.flags & (TypeFlags.Object | TypeFlags.NonPrimitive)) : + target === globalFunctionType ? !!(source.flags & TypeFlags.Object) && isFunctionObjectType(source as ObjectType) : hasBaseType(source, getTargetType(target)); } @@ -10580,7 +10704,7 @@ namespace ts { function checkTypeRelatedToAndOptionallyElaborate(source: Type, target: Type, relation: Map, errorNode: Node | undefined, expr: Expression | undefined, headMessage?: DiagnosticMessage, containingMessageChain?: () => DiagnosticMessageChain | undefined): boolean { if (isTypeRelatedTo(source, target, relation)) return true; - if (!errorNode || !elaborateError(expr, source, target)) { + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; @@ -10590,25 +10714,91 @@ namespace ts { return !!(type.flags & TypeFlags.Conditional || (type.flags & TypeFlags.Intersection && some((type as IntersectionType).types, isOrHasGenericConditional))); } - function elaborateError(node: Expression | undefined, source: Type, target: Type): boolean { + function elaborateError(node: Expression | undefined, source: Type, target: Type, relation: Map, headMessage: DiagnosticMessage | undefined): boolean { if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case SyntaxKind.JsxExpression: case SyntaxKind.ParenthesizedExpression: - return elaborateError((node as ParenthesizedExpression | JsxExpression).expression, source, target); + return elaborateError((node as ParenthesizedExpression | JsxExpression).expression, source, target, relation, headMessage); case SyntaxKind.BinaryExpression: switch ((node as BinaryExpression).operatorToken.kind) { case SyntaxKind.EqualsToken: case SyntaxKind.CommaToken: - return elaborateError((node as BinaryExpression).right, source, target); + return elaborateError((node as BinaryExpression).right, source, target, relation, headMessage); } break; case SyntaxKind.ObjectLiteralExpression: - return elaborateObjectLiteral(node as ObjectLiteralExpression, source, target); + return elaborateObjectLiteral(node as ObjectLiteralExpression, source, target, relation); case SyntaxKind.ArrayLiteralExpression: - return elaborateArrayLiteral(node as ArrayLiteralExpression, source, target); + return elaborateArrayLiteral(node as ArrayLiteralExpression, source, target, relation); case SyntaxKind.JsxAttributes: - return elaborateJsxAttributes(node as JsxAttributes, source, target); + return elaborateJsxAttributes(node as JsxAttributes, source, target, relation); + case SyntaxKind.ArrowFunction: + return elaborateArrowFunction(node as ArrowFunction, source, target, relation); + } + return false; + } + + function elaborateDidYouMeanToCallOrConstruct(node: Expression, source: Type, target: Type, relation: Map, headMessage: DiagnosticMessage | undefined): boolean { + const callSignatures = getSignaturesOfType(source, SignatureKind.Call); + const constructSignatures = getSignaturesOfType(source, SignatureKind.Construct); + for (const signatures of [constructSignatures, callSignatures]) { + if (some(signatures, s => { + const returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (TypeFlags.Any | TypeFlags.Never)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + const resultObj: { error?: Diagnostic } = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + const diagnostic = resultObj.error!; + addRelatedInfo(diagnostic, createDiagnosticForNode( + node, + signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression + )); + return true; + } + } + return false; + } + + function elaborateArrowFunction(node: ArrowFunction, source: Type, target: Type, relation: Map): boolean { + // Don't elaborate blocks + if (isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (some(node.parameters, ts.hasType)) { + return false; + } + const sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + const targetSignatures = getSignaturesOfType(target, SignatureKind.Call); + if (!length(targetSignatures)) { + return false; + } + const returnExpression = node.body; + const sourceReturn = getReturnTypeOfSignature(sourceSig); + const targetReturn = getUnionType(map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + const elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + const resultObj: { error?: Diagnostic } = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, createDiagnosticForNode( + target.symbol.declarations[0], + Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature, + )); + } + return true; + } } return false; } @@ -10619,15 +10809,15 @@ namespace ts { * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator: ElaborationIterator, source: Type, target: Type) { + function elaborateElementwise(iterator: ElaborationIterator, source: Type, target: Type, relation: Map) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span let reportedError = false; for (let status = iterator.next(); !status.done; status = iterator.next()) { const { errorNode: prop, innerExpression: next, nameType, errorMessage } = status.value; const sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); const targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); - if (sourcePropType !== errorType && targetPropType !== errorType && !isTypeAssignableTo(sourcePropType, targetPropType)) { - const elaborated = next && elaborateError(next, sourcePropType, targetPropType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + const elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -10636,10 +10826,10 @@ namespace ts { const resultObj: { error?: Diagnostic } = {}; // Use the expression type, if available const specificSource = next ? checkExpressionForMutableLocation(next, CheckMode.Normal, sourcePropType) : sourcePropType; - const result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { const reportedDiag = resultObj.error; @@ -10651,19 +10841,22 @@ namespace ts { const indexInfo = isTypeAssignableToKind(nameType, TypeFlags.NumberLike) && getIndexInfoOfType(target, IndexKind.Number) || getIndexInfoOfType(target, IndexKind.String) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, createDiagnosticForNode(indexInfo.declaration, Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && length(targetProp.declarations) || target.symbol && length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, createDiagnosticForNode( - targetProp && length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], - Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, - propertyName && !(nameType.flags & TypeFlags.UniqueESSymbol) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), - typeToString(target) - )); + const targetNode = targetProp && length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, createDiagnosticForNode( + targetNode, + Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, + propertyName && !(nameType.flags & TypeFlags.UniqueESSymbol) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), + typeToString(target) + )); + } } } reportedError = true; @@ -10681,8 +10874,8 @@ namespace ts { } } - function elaborateJsxAttributes(node: JsxAttributes, source: Type, target: Type) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node: JsxAttributes, source: Type, target: Type, relation: Map) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function *generateLimitedTupleElements(node: ArrayLiteralExpression, target: Type): ElaborationIterator { @@ -10698,9 +10891,14 @@ namespace ts { } } - function elaborateArrayLiteral(node: ArrayLiteralExpression, source: Type, target: Type) { + function elaborateArrayLiteral(node: ArrayLiteralExpression, source: Type, target: Type, relation: Map) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + const tupleizedType = checkArrayLiteral(node, CheckMode.Contextual, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -10729,8 +10927,8 @@ namespace ts { } } - function elaborateObjectLiteral(node: ObjectLiteralExpression, source: Type, target: Type) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node: ObjectLiteralExpression, source: Type, target: Type, relation: Map) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** @@ -10839,13 +11037,13 @@ namespace ts { } if (!ignoreReturnTypes) { - const targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol)! : getReturnTypeOfSignature(target); + const targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol)! : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - const sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol)! : getReturnTypeOfSignature(source); + const sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol)! : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions const targetTypePredicate = getTypePredicateOfSignature(target); @@ -11015,11 +11213,11 @@ namespace ts { } function isTypeRelatedTo(source: Type, target: Type, relation: Map) { - if (source.flags & TypeFlags.StringOrNumberLiteral && source.flags & TypeFlags.FreshLiteral) { - source = (source).regularType; + if (source.flags & TypeFlags.Literal && source.flags & TypeFlags.FreshLiteral) { + source = (source).regularType; } - if (target.flags & TypeFlags.StringOrNumberLiteral && target.flags & TypeFlags.FreshLiteral) { - target = (target).regularType; + if (target.flags & TypeFlags.Literal && target.flags & TypeFlags.FreshLiteral) { + target = (target).regularType; } if (source === target || relation === comparableRelation && !(target.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(target, source, relation) || @@ -11070,7 +11268,6 @@ namespace ts { let depth = 0; let expandingFlags = ExpandingFlags.None; let overflow = false; - let isIntersectionConstituent = false; Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); @@ -11173,12 +11370,12 @@ namespace ts { * * Ternary.Maybe if they are related with assumptions of other relationships, or * * Ternary.False if they are not related. */ - function isRelatedTo(source: Type, target: Type, reportErrors = false, headMessage?: DiagnosticMessage): Ternary { - if (source.flags & TypeFlags.StringOrNumberLiteral && source.flags & TypeFlags.FreshLiteral) { - source = (source).regularType; + function isRelatedTo(source: Type, target: Type, reportErrors = false, headMessage?: DiagnosticMessage, isApparentIntersectionConstituent?: boolean): Ternary { + if (source.flags & TypeFlags.Literal && source.flags & TypeFlags.FreshLiteral) { + source = (source).regularType; } - if (target.flags & TypeFlags.StringOrNumberLiteral && target.flags & TypeFlags.FreshLiteral) { - target = (target).regularType; + if (target.flags & TypeFlags.Literal && target.flags & TypeFlags.FreshLiteral) { + target = (target).regularType; } if (source.flags & TypeFlags.Substitution) { source = relation === definitelyAssignableRelation ? (source).typeVariable : (source).substitute; @@ -11220,6 +11417,7 @@ namespace ts { if (relation === comparableRelation && !(target.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return Ternary.True; + const isComparingJsxAttributes = !!(getObjectFlags(source) & ObjectFlags.JsxAttributes); if (isObjectLiteralType(source) && source.flags & TypeFlags.FreshLiteral) { const discriminantType = target.flags & TypeFlags.Union ? findMatchingDiscriminantType(source, target as UnionType) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { @@ -11237,11 +11435,11 @@ namespace ts { } } - if (relation !== comparableRelation && !isIntersectionConstituent && + if (relation !== comparableRelation && !isApparentIntersectionConstituent && source.flags & (TypeFlags.Primitive | TypeFlags.Object | TypeFlags.Intersection) && source !== globalObjectType && target.flags & (TypeFlags.Object | TypeFlags.Intersection) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - !hasCommonProperties(source, target)) { + !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { const calls = getSignaturesOfType(source, SignatureKind.Call); const constructs = getSignaturesOfType(source, SignatureKind.Construct); @@ -11258,8 +11456,7 @@ namespace ts { let result = Ternary.False; const saveErrorInfo = errorInfo; - const saveIsIntersectionConstituent = isIntersectionConstituent; - isIntersectionConstituent = false; + let isIntersectionConstituent = !!isApparentIntersectionConstituent; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), @@ -11274,7 +11471,7 @@ namespace ts { result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & TypeFlags.Primitive) && !(target.flags & TypeFlags.Primitive)); } else if (target.flags & TypeFlags.Intersection) { - isIntersectionConstituent = true; + isIntersectionConstituent = true; // set here to affect the following trio of checks result = typeRelatedToEachType(source, target as IntersectionType, reportErrors); } else if (source.flags & TypeFlags.Intersection) { @@ -11294,7 +11491,7 @@ namespace ts { result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } if (!result && (source.flags & TypeFlags.StructuredOrInstantiable || target.flags & TypeFlags.StructuredOrInstantiable)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } @@ -11311,14 +11508,12 @@ namespace ts { // 'string & number | number & number' which reduces to just 'number'. const constraint = getUnionConstraintOfIntersection(source, !!(target.flags & TypeFlags.Union)); if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - isIntersectionConstituent = saveIsIntersectionConstituent; - if (!result && reportErrors) { if (source.flags & TypeFlags.Object && target.flags & TypeFlags.Primitive) { tryElaborateErrorsForPrimitivesAndObjects(source, target); @@ -11345,7 +11540,7 @@ namespace ts { let result: Ternary; const flags = source.flags & target.flags; if (flags & TypeFlags.Object || flags & TypeFlags.IndexedAccess || flags & TypeFlags.Conditional || flags & TypeFlags.Index || flags & TypeFlags.Substitution) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); } if (flags & (TypeFlags.Union | TypeFlags.Intersection)) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -11372,15 +11567,16 @@ namespace ts { return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } for (const prop of getPropertiesOfObjectType(source)) { - if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. if (!errorNode) return Debug.fail(); - if (isJsxAttributes(errorNode) || isJsxOpeningLikeElement(errorNode)) { + if (isJsxAttributes(errorNode) || isJsxOpeningLikeElement(errorNode) || isJsxOpeningLikeElement(errorNode.parent)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) reportError(Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { @@ -11416,8 +11612,8 @@ namespace ts { return false; } - function isPropertyFromSpread(prop: Symbol, container: Symbol) { - return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + function shouldCheckAsExcessProperty(prop: Symbol, container: Symbol) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; } function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType): Ternary { @@ -11491,34 +11687,21 @@ namespace ts { // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source: Type, target: UnionOrIntersectionType) { - let match: Type | undefined; const sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (const sourceProperty of sourcePropertiesFiltered) { - const sourceType = getTypeOfSymbol(sourceProperty); - for (const type of target.types) { - const targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, p => ([() => getTypeOfSymbol(p), p.escapedName] as [() => Type, __String])), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source: Type, target: IntersectionType, reportErrors: boolean): Ternary { let result = Ternary.True; const targetTypes = target.types; for (const targetType of targetTypes) { - const related = isRelatedTo(source, targetType, reportErrors); + const related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); if (!related) { return Ternary.False; } @@ -11612,7 +11795,7 @@ namespace ts { // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function recursiveTypeRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary { + function recursiveTypeRelatedTo(source: Type, target: Type, reportErrors: boolean, isIntersectionConstituent: boolean): Ternary { if (overflow) { return Ternary.False; } @@ -11653,7 +11836,7 @@ namespace ts { const saveExpandingFlags = expandingFlags; if (!(expandingFlags & ExpandingFlags.Source) && isDeeplyNestedType(source, sourceStack, depth)) expandingFlags |= ExpandingFlags.Source; if (!(expandingFlags & ExpandingFlags.Target) && isDeeplyNestedType(target, targetStack, depth)) expandingFlags |= ExpandingFlags.Target; - const result = expandingFlags !== ExpandingFlags.Both ? structuredTypeRelatedTo(source, target, reportErrors) : Ternary.Maybe; + const result = expandingFlags !== ExpandingFlags.Both ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : Ternary.Maybe; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -11678,7 +11861,7 @@ namespace ts { return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } - function structuredTypeRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary { + function structuredTypeRelatedTo(source: Type, target: Type, reportErrors: boolean, isIntersectionConstituent: boolean): Ternary { const flags = source.flags & target.flags; if (relation === identityRelation && !(flags & TypeFlags.Object)) { if (flags & TypeFlags.Index) { @@ -11738,15 +11921,20 @@ namespace ts { const simplified = getSimplifiedType((target).type); const constraint = simplified !== (target).type ? simplified : getConstraintOfType((target).type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, (target as IndexType).stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, (target as IndexType).stringsOnly), reportErrors) === Ternary.True) { + return Ternary.True; } } } } else if (target.flags & TypeFlags.IndexedAccess) { - // A type S is related to a type T[K] if S is related to C, where C is the base constraint of T[K] - if (relation !== identityRelation) { + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType((target).objectType) && isGenericIndexType((target).indexType))) { const constraint = getBaseConstraintOfType(target); if (constraint && constraint !== target) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -11796,7 +11984,7 @@ namespace ts { } else { const instantiated = getTypeWithThisArgument(constraint, source); - if (result = isRelatedTo(instantiated, target, reportErrors)) { + if (result = isRelatedTo(instantiated, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; return result; } @@ -12109,8 +12297,8 @@ namespace ts { return Ternary.True; } - const sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - const targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + const sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + const targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); const sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === SignatureKind.Construct) ? SignatureKind.Call : kind); @@ -12321,6 +12509,25 @@ namespace ts { } } + function discriminateTypeByDiscriminableItems(target: UnionType, discriminators: [() => Type, __String][], related: (source: Type, target: Type) => boolean | Ternary): Type | undefined; + function discriminateTypeByDiscriminableItems(target: UnionType, discriminators: [() => Type, __String][], related: (source: Type, target: Type) => boolean | Ternary, defaultValue: Type): Type; + function discriminateTypeByDiscriminableItems(target: UnionType, discriminators: [() => Type, __String][], related: (source: Type, target: Type) => boolean | Ternary, defaultValue?: Type) { + let match: Type | undefined; + for (const [getDiscriminatingType, propertyName] of discriminators) { + for (const type of target.types) { + const targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** * A type is 'weak' if it is an object type with at least one optional property * and no required properties, call/construct signatures or index signatures @@ -12339,8 +12546,7 @@ namespace ts { return false; } - function hasCommonProperties(source: Type, target: Type) { - const isComparingJsxAttributes = !!(getObjectFlags(source) & ObjectFlags.JsxAttributes); + function hasCommonProperties(source: Type, target: Type, isComparingJsxAttributes: boolean) { for (const prop of getPropertiesOfType(source)) { if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { return true; @@ -12714,9 +12920,14 @@ namespace ts { } function getTupleElementType(type: Type, index: number) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments![index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index as __String); + const propType = getTypeOfPropertyOfType(type, "" + index as __String); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, t => !(t).target.hasRestElement)) { + return mapType(type, t => getRestTypeOfTupleType(t) || undefinedType); + } + return undefined; } function isNeitherUnitTypeNorNever(type: Type): boolean { @@ -12746,7 +12957,7 @@ namespace ts { return type.flags & TypeFlags.EnumLiteral && type.flags & TypeFlags.FreshLiteral ? getBaseTypeOfEnumLiteralType(type) : type.flags & TypeFlags.StringLiteral && type.flags & TypeFlags.FreshLiteral ? stringType : type.flags & TypeFlags.NumberLiteral && type.flags & TypeFlags.FreshLiteral ? numberType : - type.flags & TypeFlags.BooleanLiteral ? booleanType : + type.flags & TypeFlags.BooleanLiteral && type.flags & TypeFlags.FreshLiteral ? booleanType : type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getWidenedLiteralType)) : type; } @@ -12800,7 +13011,7 @@ namespace ts { return type.flags & TypeFlags.Union ? getFalsyFlagsOfTypes((type).types) : type.flags & TypeFlags.StringLiteral ? (type).value === "" ? TypeFlags.StringLiteral : 0 : type.flags & TypeFlags.NumberLiteral ? (type).value === 0 ? TypeFlags.NumberLiteral : 0 : - type.flags & TypeFlags.BooleanLiteral ? type === falseType ? TypeFlags.BooleanLiteral : 0 : + type.flags & TypeFlags.BooleanLiteral ? (type === falseType || type === regularFalseType) ? TypeFlags.BooleanLiteral : 0 : type.flags & TypeFlags.PossiblyFalsy; } @@ -12817,7 +13028,8 @@ namespace ts { function getDefinitelyFalsyPartOfType(type: Type): Type { return type.flags & TypeFlags.String ? emptyStringType : type.flags & TypeFlags.Number ? zeroType : - type.flags & TypeFlags.Boolean || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null) || type.flags & TypeFlags.StringLiteral && (type).value === "" || type.flags & TypeFlags.NumberLiteral && (type).value === 0 ? type : @@ -13075,8 +13287,12 @@ namespace ts { return errorReported; } - function reportImplicitAnyError(declaration: Declaration, type: Type) { + function reportImplicitAny(declaration: Declaration, type: Type) { const typeAsString = typeToString(getWidenedType(type)); + if (isInJSFile(declaration) && !isCheckJsEnabledForFile(getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } let diagnostic: DiagnosticMessage; switch (declaration.kind) { case SyntaxKind.BinaryExpression: @@ -13099,26 +13315,28 @@ namespace ts { case SyntaxKind.SetAccessor: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - if (!(declaration as NamedDeclaration).name) { + if (noImplicitAny && !(declaration as NamedDeclaration).name) { error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case SyntaxKind.MappedType: - error(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration: Declaration, type: Type) { if (produceDiagnostics && noImplicitAny && type.flags & TypeFlags.ContainsWideningType) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } @@ -13128,10 +13346,8 @@ namespace ts { const targetCount = getParameterCount(target); const sourceRestType = getEffectiveRestType(source); const targetRestType = getEffectiveRestType(target); - const paramCount = targetRestType ? Math.min(targetCount - 1, sourceCount) : - sourceRestType ? targetCount : - Math.min(sourceCount, targetCount); - + const targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + const paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); const sourceThisType = getThisTypeOfSignature(source); if (sourceThisType) { const targetThisType = getThisTypeOfSignature(target); @@ -13333,10 +13549,12 @@ namespace ts { let symbolStack: Symbol[]; let visited: Map; let contravariant = false; + let bivariant = false; let propagationType: Type; + let allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); - function inferFromTypes(source: Type, target: Type) { + function inferFromTypes(source: Type, target: Type): void { if (!couldContainTypeVariables(target)) { return; } @@ -13418,11 +13636,13 @@ namespace ts { } if (priority === inference.priority) { const candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = append(inference.candidates, candidate); + inference.candidates = appendIfUnique(inference.candidates, candidate); } } if (!(priority & InferencePriority.ReturnType) && target.flags & TypeFlags.TypeParameter && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -13431,6 +13651,17 @@ namespace ts { } return; } + else { + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + const simplified = getSimplifiedType(target); + if (simplified !== target) { + const key = source.id + "," + simplified.id; + if (!visited || !visited.get(key)) { + (visited || (visited = createMap())).set(key, true); + inferFromTypes(source, simplified); + } + } + } } if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) { // If source and target are references to the same generic type, infer from type arguments @@ -13471,6 +13702,9 @@ namespace ts { inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & TypeFlags.Conditional) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & TypeFlags.UnionOrIntersection) { const targetTypes = (target).types; let typeVariableCount = 0; @@ -13504,7 +13738,22 @@ namespace ts { } else { if (!(priority & InferencePriority.NoConstraints && source.flags & (TypeFlags.Intersection | TypeFlags.Instantiable))) { - source = getApparentType(source); + const apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (TypeFlags.Object | TypeFlags.Intersection))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (TypeFlags.Object | TypeFlags.Intersection)) { const key = source.id + "," + target.id; @@ -13652,7 +13901,12 @@ namespace ts { function inferFromSignature(source: Signature, target: Signature, skipParameters: boolean) { if (!skipParameters) { + const saveBivariant = bivariant; + const kind = target.declaration ? target.declaration.kind : SyntaxKind.Unknown; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === SyntaxKind.MethodDeclaration || kind === SyntaxKind.MethodSignature || kind === SyntaxKind.Constructor; forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; } const sourceTypePredicate = getTypePredicateOfSignature(source); const targetTypePredicate = getTypePredicateOfSignature(target); @@ -13710,7 +13964,7 @@ namespace ts { function hasPrimitiveConstraint(type: TypeParameter): boolean { const constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, TypeFlags.Primitive | TypeFlags.Index); + return !!constraint && maybeTypeOfKind(constraint.flags & TypeFlags.Conditional ? getDefaultConstraintOfConditionalType(constraint as ConditionalType) : constraint, TypeFlags.Primitive | TypeFlags.Index); } function isObjectLiteralType(type: Type) { @@ -13759,15 +14013,17 @@ namespace ts { if (!inferredType) { const signature = context.signature; if (signature) { - if (inference.contraCandidates && (!inference.candidates || inference.candidates.length === 1 && inference.candidates[0].flags & TypeFlags.Never)) { - // If we have contravariant inferences, but no covariant inferences or a single - // covariant inference of 'never', we find the best common subtype and treat that - // as a single covariant candidate. - inference.candidates = [getContravariantInference(inference)]; - inference.contraCandidates = undefined; + const inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + if (inference.contraCandidates) { + const inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & TypeFlags.Never) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } else if (context.flags & InferenceFlags.NoDefault) { // We use silentNeverType as the wildcard that signals no inferences. @@ -13825,6 +14081,36 @@ namespace ts { // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name: __String): DiagnosticMessage { + switch (name) { + case "document": + case "console": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return Diagnostics.Cannot_find_name_0; + } + } + function getResolvedSymbol(node: Identifier): Symbol { const links = getNodeLinks(node); if (!links.resolvedSymbol) { @@ -13833,7 +14119,7 @@ namespace ts { node, node.escapedText, SymbolFlags.Value | SymbolFlags.ExportValue, - Diagnostics.Cannot_find_name_0, + getCannotFindNameDiagnosticForName(node.escapedText), node, !isWriteOnlyAccess(node), /*excludeGlobals*/ false, @@ -13968,14 +14254,28 @@ namespace ts { return undefined; } + function isDiscriminantType(type: Type): boolean { + if (type.flags & TypeFlags.Union) { + if (type.flags & (TypeFlags.Boolean | TypeFlags.EnumLiteral)) { + return true; + } + let combined = 0; + for (const t of (type).types) combined |= t.flags; + if (combined & TypeFlags.Unit && !(combined & TypeFlags.Instantiable)) { + return true; + } + } + return false; + } + function isDiscriminantProperty(type: Type | undefined, name: __String) { if (type && type.flags & TypeFlags.Union) { const prop = getUnionOrIntersectionProperty(type, name); if (prop && getCheckFlags(prop) & CheckFlags.SyntheticProperty) { if ((prop).isDiscriminantProperty === undefined) { - (prop).isDiscriminantProperty = !!((prop).checkFlags & CheckFlags.HasNonUniformType) && isLiteralType(getTypeOfSymbol(prop)); + (prop).isDiscriminantProperty = !!((prop).checkFlags & CheckFlags.HasNonUniformType) && isDiscriminantType(getTypeOfSymbol(prop)); } - return (prop).isDiscriminantProperty; + return !!(prop).isDiscriminantProperty; } } return false; @@ -14042,7 +14342,10 @@ namespace ts { if (assignedType.flags & TypeFlags.Never) { return assignedType; } - const reducedType = filterType(declaredType, t => typeMaybeAssignableTo(assignedType, t)); + let reducedType = filterType(declaredType, t => typeMaybeAssignableTo(assignedType, t)); + if (assignedType.flags & TypeFlags.FreshLiteral && assignedType.flags & TypeFlags.BooleanLiteral) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } // Our crude heuristic produces an invalid result in some cases: see GH#26130. // For now, when that happens, we give up and don't narrow at all. (This also // means we'll never narrow for erroneous assignments where the assigned type @@ -14095,13 +14398,15 @@ namespace ts { } if (flags & TypeFlags.BooleanLike) { return strictNullChecks ? - type === falseType ? TypeFacts.FalseStrictFacts : TypeFacts.TrueStrictFacts : - type === falseType ? TypeFacts.FalseFacts : TypeFacts.TrueFacts; + (type === falseType || type === regularFalseType) ? TypeFacts.FalseStrictFacts : TypeFacts.TrueStrictFacts : + (type === falseType || type === regularFalseType) ? TypeFacts.FalseFacts : TypeFacts.TrueFacts; } if (flags & TypeFlags.Object) { - return isFunctionObjectType(type) ? - strictNullChecks ? TypeFacts.FunctionStrictFacts : TypeFacts.FunctionFacts : - strictNullChecks ? TypeFacts.ObjectStrictFacts : TypeFacts.ObjectFacts; + return getObjectFlags(type) & ObjectFlags.Anonymous && isEmptyObjectType(type) ? + strictNullChecks ? TypeFacts.EmptyObjectStrictFacts : TypeFacts.EmptyObjectFacts : + isFunctionObjectType(type) ? + strictNullChecks ? TypeFacts.FunctionStrictFacts : TypeFacts.FunctionFacts : + strictNullChecks ? TypeFacts.ObjectStrictFacts : TypeFacts.ObjectFacts; } if (flags & (TypeFlags.Void | TypeFlags.Undefined)) { return TypeFacts.UndefinedFacts; @@ -14145,7 +14450,7 @@ namespace ts { } function getTypeOfDestructuredArrayElement(type: Type, index: number) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -14343,6 +14648,10 @@ namespace ts { return type.flags & TypeFlags.Union ? forEach((type).types, f) : f(type); } + function everyType(type: Type, f: (t: Type) => boolean): boolean { + return type.flags & TypeFlags.Union ? every((type).types, f) : f(type); + } + function filterType(type: Type, f: (t: Type) => boolean): Type { if (type.flags & TypeFlags.Union) { const types = (type).types; @@ -14664,6 +14973,14 @@ namespace ts { // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConst(node))) { + const init = getDeclaredExpandoInitializer(node); + if (init && (init.kind === SyntaxKind.FunctionExpression || init.kind === SyntaxKind.ArrowFunction)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -14726,9 +15043,12 @@ namespace ts { } function getTypeAtSwitchClause(flow: FlowSwitchClause): FlowType { + const expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } const flowType = getTypeAtFlowNode(flow.antecedent); let type = getTypeFromFlowType(flowType); - const expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } @@ -15013,23 +15333,24 @@ namespace ts { return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); function narrowTypeForTypeof(type: Type) { - if (assumeTrue && !(type.flags & TypeFlags.Union)) { - if (type.flags & TypeFlags.Unknown && literal.text === "object") { - return getUnionType([nonPrimitiveType, nullType]); + if (type.flags & TypeFlags.Unknown && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. + const targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; } - // We narrow a non-union type to an exact primitive type if the non-union type - // is a supertype of that primitive type. For example, type 'any' can be narrowed - // to one of the primitive types. - const targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); - if (targetType) { - if (isTypeSubtypeOf(targetType, type)) { - return isTypeAny(type) ? targetType : getIntersectionType([type, targetType]); // Intersection to handle `string` being a subtype of `keyof T` - } - if (type.flags & TypeFlags.Instantiable) { - const constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(targetType, constraint)) { - return getIntersectionType([type, targetType]); - } + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & TypeFlags.Instantiable) { + const constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); } } } @@ -15146,7 +15467,7 @@ namespace ts { // Check that right operand is a function type with a prototype property const rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } @@ -15166,24 +15487,13 @@ namespace ts { } if (!targetType) { - // Target type is type of construct signature - let constructSignatures: ReadonlyArray | undefined; - if (getObjectFlags(rightType) & ObjectFlags.Interface) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (getObjectFlags(rightType) & ObjectFlags.Anonymous) { - constructSignatures = getSignaturesOfType(rightType, SignatureKind.Construct); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(map(constructSignatures, signature => getReturnTypeOfSignature(getErasedSignature(signature)))); - } + const constructSignatures = getSignaturesOfType(rightType, SignatureKind.Construct); + targetType = constructSignatures.length ? + getUnionType(map(constructSignatures, signature => getReturnTypeOfSignature(getErasedSignature(signature)))) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type: Type, candidate: Type, assumeTrue: boolean, isRelated: (source: Type, target: Type) => boolean) { @@ -15466,7 +15776,7 @@ namespace ts { if (assignmentKind) { if (!(localOrExportSymbol.flags & SymbolFlags.Variable) && - !(isInJavaScriptFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule)) { + !(isInJSFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule)) { error(node, Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -15550,6 +15860,10 @@ namespace ts { return !!findAncestor(node, n => n === threshold ? "quit" : isFunctionLike(n)); } + function getPartOfForStatementContainingNode(node: Node, container: ForStatement) { + return findAncestor(node, n => n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement); + } + function checkNestedBlockScopedBinding(node: Identifier, symbol: Symbol): void { if (languageVersion >= ScriptTarget.ES2015 || (symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.Class)) === 0 || @@ -15578,7 +15892,25 @@ namespace ts { if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding; + let capturesBlockScopeBindingInLoopBody = true; + if (isForStatement(container) && + getAncestor(symbol.valueDeclaration, SyntaxKind.VariableDeclarationList)!.parent === container) { + const part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + const links = getNodeLinks(part); + links.flags |= NodeCheckFlags.ContainsCapturedBlockScopeBinding; + + const capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + pushIfUnique(capturedBindings, symbol); + + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. @@ -15598,6 +15930,11 @@ namespace ts { } } + function isBindingCapturedByNode(node: Node, decl: VariableDeclaration | BindingElement) { + const links = getNodeLinks(node); + return !!links && contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } + function isAssignedInBodyOfForStatement(node: Identifier, container: ForStatement): boolean { // skip parenthesized nodes let current: Node = node; @@ -15759,32 +16096,29 @@ namespace ts { } function tryGetThisTypeAt(node: Node, container = getThisContainer(node, /*includeArrowFunctions*/ false)): Type | undefined { + const isInJS = isInJSFile(node); if (isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. - // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === SyntaxKind.FunctionExpression && - container.parent.kind === SyntaxKind.BinaryExpression && - getSpecialPropertyAssignmentKind(container.parent as BinaryExpression) === SpecialPropertyAssignmentKind.PrototypeProperty) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - const className = (((container.parent as BinaryExpression) // x.prototype.y = f - .left as PropertyAccessExpression) // x.prototype.y - .expression as PropertyAccessExpression) // x.prototype - .expression; // x + const className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { const classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & SymbolFlags.Function)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + const classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) && + else if (isInJS && + (container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) && getJSDocClassTag(container)) { - const classType = getJavascriptClassType(container.symbol); + const classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -15802,7 +16136,7 @@ namespace ts { return getFlowTypeOfReference(node, type); } - if (isInJavaScriptFile(node)) { + if (isInJS) { const type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); @@ -15810,6 +16144,34 @@ namespace ts { } } + function getClassNameFromPrototypeMethod(container: Node) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === SyntaxKind.FunctionExpression && + isBinaryExpression(container.parent) && + getAssignmentDeclarationKind(container.parent) === AssignmentDeclarationKind.PrototypeProperty) { + // Get the 'x' of 'x.prototype.y = container' + return ((container.parent // x.prototype.y = container + .left as PropertyAccessExpression) // x.prototype.y + .expression as PropertyAccessExpression) // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === SyntaxKind.MethodDeclaration && + container.parent.kind === SyntaxKind.ObjectLiteralExpression && + isBinaryExpression(container.parent.parent) && + getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.Prototype) { + return (container.parent.parent.left as PropertyAccessExpression).expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === SyntaxKind.FunctionExpression && + container.parent.kind === SyntaxKind.PropertyAssignment && + container.parent.parent.kind === SyntaxKind.ObjectLiteralExpression && + isBinaryExpression(container.parent.parent.parent) && + getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.Prototype) { + return (container.parent.parent.parent.left as PropertyAccessExpression).expression; + } + } + function getTypeForThisExpressionFromJSDoc(node: Node) { const jsdocType = getJSDocType(node); if (jsdocType && jsdocType.kind === SyntaxKind.JSDocFunctionType) { @@ -15904,16 +16266,18 @@ namespace ts { // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -15925,19 +16289,20 @@ namespace ts { // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === SyntaxKind.MethodDeclaration && hasModifier(container, ModifierFlags.Async)) { if (isSuperProperty(node.parent) && isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= NodeCheckFlags.AsyncMethodWithSuperBinding; @@ -16059,7 +16424,7 @@ namespace ts { } } } - const inJs = isInJavaScriptFile(func); + const inJs = isInJSFile(func); if (noImplicitThis || inJs) { const containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -16188,9 +16553,22 @@ namespace ts { } const contextualReturnType = getContextualReturnType(func); - return functionFlags & FunctionFlags.Async - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & FunctionFlags.Async) { // Async function + const contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + + function getContextualTypeForAwaitOperand(node: AwaitExpression): Type | undefined { + const contextualType = getContextualType(node); + if (contextualType) { + const contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -16253,6 +16631,9 @@ namespace ts { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. const signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } return getTypeAtPosition(signature, argIndex); } @@ -16282,7 +16663,7 @@ namespace ts { // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` const type = getContextualType(binaryExpression); - return !type && node === right && !isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.CommaToken: @@ -16293,16 +16674,16 @@ namespace ts { } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getIsContextSensitiveAssignmentOrContextType(binaryExpression: BinaryExpression): boolean | Type { - const kind = getSpecialPropertyAssignmentKind(binaryExpression); + const kind = getAssignmentDeclarationKind(binaryExpression); switch (kind) { - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.None: return true; - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.Prototype: - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.Prototype: + case AssignmentDeclarationKind.PrototypeProperty: // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. if (!binaryExpression.left.symbol) { @@ -16330,10 +16711,10 @@ namespace ts { return false; } } - return !isInJavaScriptFile(decl); + return !isInJSFile(decl); } - case SpecialPropertyAssignmentKind.ModuleExports: - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ModuleExports: + case AssignmentDeclarationKind.ThisProperty: if (!binaryExpression.symbol) return true; if (binaryExpression.symbol.valueDeclaration) { const annotated = getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); @@ -16344,7 +16725,7 @@ namespace ts { } } } - if (kind === SpecialPropertyAssignmentKind.ModuleExports) return false; + if (kind === AssignmentDeclarationKind.ModuleExports) return false; const thisAccess = binaryExpression.left as PropertyAccessExpression; if (!isObjectLiteralMethod(getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return false; @@ -16369,6 +16750,8 @@ namespace ts { return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, IndexKind.Number) || + getIndexTypeOfContextualType(t, IndexKind.String); } return undefined; }, /*noReductions*/ true); @@ -16378,11 +16761,6 @@ namespace ts { return mapType(type, t => getIndexTypeOfStructuredType(t, kind), /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type: Type): boolean { - return !!(type.flags & TypeFlags.Union ? forEach((type).types, isTupleLikeType) : isTupleLikeType(type)); - } - // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -16479,43 +16857,53 @@ namespace ts { case SyntaxKind.FalseKeyword: case SyntaxKind.NullKeyword: case SyntaxKind.Identifier: + case SyntaxKind.UndefinedKeyword: return true; case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ParenthesizedExpression: return isPossiblyDiscriminantValue((node).expression); + case SyntaxKind.JsxExpression: + return !(node as JsxExpression).expression || isPossiblyDiscriminantValue((node as JsxExpression).expression!); } return false; } + function discriminateContextualTypeByObjectMembers(node: ObjectLiteralExpression, contextualType: UnionType) { + return discriminateTypeByDiscriminableItems(contextualType, + map( + filter(node.properties, p => !!p.symbol && p.kind === SyntaxKind.PropertyAssignment && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName)), + prop => ([() => checkExpression((prop as PropertyAssignment).initializer), prop.symbol.escapedName] as [() => Type, __String]) + ), + isTypeAssignableTo, + contextualType + ); + } + + function discriminateContextualTypeByJSXAttributes(node: JsxAttributes, contextualType: UnionType) { + return discriminateTypeByDiscriminableItems(contextualType, + map( + filter(node.properties, p => !!p.symbol && p.kind === SyntaxKind.JsxAttribute && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), + prop => ([!(prop as JsxAttribute).initializer ? (() => trueType) : (() => checkExpression((prop as JsxAttribute).initializer!)), prop.symbol.escapedName] as [() => Type, __String]) + ), + isTypeAssignableTo, + contextualType + ); + } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node: Expression): Type | undefined { let contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & TypeFlags.Union && isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - let match: Type | undefined; - propLoop: for (const prop of node.properties) { - if (!prop.symbol) continue; - if (prop.kind !== SyntaxKind.PropertyAssignment) continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - const discriminatingType = checkExpression(prop.initializer); - for (const type of (contextualType as UnionType).types) { - const targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & TypeFlags.Union) { + if (isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType as UnionType); + } + else if (isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType as UnionType); } } - return match || contextualType; + return contextualType; } /** @@ -16556,7 +16944,9 @@ namespace ts { return getContextualTypeForReturnExpression(node); case SyntaxKind.YieldExpression: return getContextualTypeForYieldOperand(parent); - case SyntaxKind.CallExpression: + case SyntaxKind.AwaitExpression: + return getContextualTypeForAwaitOperand(parent); + case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: return getContextualTypeForArgument(parent, node); case SyntaxKind.TypeAssertionExpression: @@ -16581,7 +16971,7 @@ namespace ts { return getContextualTypeForSubstitutionExpression(parent.parent, node); case SyntaxKind.ParenthesizedExpression: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - const tag = isInJavaScriptFile(parent) ? getJSDocTypeTag(parent) : undefined; + const tag = isInJSFile(parent) ? getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression!.type) : getContextualType(parent); } case SyntaxKind.JsxExpression: @@ -16602,72 +16992,17 @@ namespace ts { } function getContextualJsxElementAttributesType(node: JsxOpeningLikeElement) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + if (isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; } - const valueType = checkExpression(node.tagName); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - - const isJs = isInJavaScriptFile(node); - return mapType(valueType, t => getJsxSignaturesParameterTypes(t, isJs, node)); + return getContextualTypeForArgumentAtIndex(node, 0); } - function getJsxSignaturesParameterTypes(valueType: Type, isJs: boolean, context: JsxOpeningLikeElement) { - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (valueType.flags & TypeFlags.String) { - return anyType; - } - else if (valueType.flags & TypeFlags.StringLiteral) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== errorType) { - const stringLiteralTypeName = (valueType).value; - const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); - if (indexSignatureType) { - return indexSignatureType; - } - } - return anyType; - } - - // Resolve the signatures, preferring constructor - let signatures = getSignaturesOfType(valueType, SignatureKind.Construct); - let ctor = true; - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, SignatureKind.Call); - ctor = false; - if (signatures.length === 0) { - // We found no signatures at all, which is an error - return errorType; - } - } - - const links = getNodeLinks(context); - if (!links.resolvedSignatures) { - links.resolvedSignatures = createMap(); - } - const cacheKey = "" + getTypeId(valueType); - const cachedResolved = links.resolvedSignatures.get(cacheKey); - if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { - signatures = cachedResolved; - } - else if (!cachedResolved) { - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); - } - - return getUnionType(map(signatures, ctor ? t => getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false) : t => getJsxPropsTypeFromCallSignature(t, context)), UnionReduction.None); + function getEffectiveFirstArgumentForJsxSignature(signature: Signature, node: JsxOpeningLikeElement) { + return isJsxStatelessFunctionReference(node) ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig: Signature, context: JsxOpeningLikeElement) { @@ -16685,23 +17020,42 @@ namespace ts { return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } + function getStaticTypeOfReferencedJsxConstructor(context: JsxOpeningLikeElement) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + const fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + const tagType = checkExpressionCached(context.tagName); + if (tagType.flags & TypeFlags.StringLiteral) { + const result = getIntrinsicAttributesTypeFromStringLiteralType(tagType as StringLiteralType, context); + if (!result) { + return errorType; + } + const fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } + function getJsxManagedAttributesFromLocatedAttributes(context: JsxOpeningLikeElement, ns: Symbol, attributesType: Type) { const managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + const ctorType = getStaticTypeOfReferencedJsxConstructor(context); if (length((declaredManagedType as GenericType).typeParameters) >= 2) { - const args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], (declaredManagedType as GenericType).typeParameters, 2, isInJavaScriptFile(context)); + const args = fillMissingTypeArguments([ctorType, attributesType], (declaredManagedType as GenericType).typeParameters, 2, isInJSFile(context)); return createTypeReference((declaredManagedType as GenericType), args); } else if (length(declaredManagedType.aliasTypeArguments) >= 2) { - const args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments!, 2, isInJavaScriptFile(context)); + const args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments!, 2, isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol!, args); } } return attributesType; } - function getJsxPropsTypeFromClassType(sig: Signature, isJs: boolean, context: JsxOpeningLikeElement, reportErrors: boolean) { + function getJsxPropsTypeFromClassType(sig: Signature, context: JsxOpeningLikeElement) { const ns = getJsxNamespaceAt(context); const forcedLookupLocation = getJsxElementPropertiesName(ns); let attributesType = forcedLookupLocation === undefined @@ -16715,7 +17069,7 @@ namespace ts { if (!attributesType) { // There is no property named 'props' on this instance type - if (reportErrors && !!forcedLookupLocation && !!length(context.attributes.properties)) { + if (!!forcedLookupLocation && !!length(context.attributes.properties)) { error(context, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, unescapeLeadingUnderscores(forcedLookupLocation)); } return emptyObjectType; @@ -16736,7 +17090,7 @@ namespace ts { const hostClassType = getReturnTypeOfSignature(sig); apparentAttributesType = intersectTypes( typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isInJSFile(context))) : intrinsicClassAttribs, apparentAttributesType ); @@ -16856,7 +17210,7 @@ namespace ts { (node.kind === SyntaxKind.BinaryExpression && (node).operatorToken.kind === SyntaxKind.EqualsToken); } - function checkArrayLiteral(node: ArrayLiteralExpression, checkMode: CheckMode | undefined): Type { + function checkArrayLiteral(node: ArrayLiteralExpression, checkMode: CheckMode | undefined, forceTuple: boolean | undefined): Type { const elements = node.elements; const elementCount = elements.length; let hasNonEndingSpreadElement = false; @@ -16878,7 +17232,7 @@ namespace ts { // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - const restArrayType = checkExpression((e).expression, checkMode); + const restArrayType = checkExpression((e).expression, checkMode, forceTuple); const restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -16887,7 +17241,7 @@ namespace ts { } else { const elementContextualType = getContextualTypeForElementExpression(contextualType, index); - const type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + const type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === SyntaxKind.SpreadElement) { @@ -16899,36 +17253,48 @@ namespace ts { const minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + let tupleResult: Type | undefined; if (inDestructuringPattern && minLength > 0) { const type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - const pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === SyntaxKind.ArrayBindingPattern || pattern.kind === SyntaxKind.ArrayLiteralExpression)) { - const patternElements = (pattern).elements; - for (let i = elementCount; i < patternElements.length; i++) { - const e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push((contextualType).typeArguments![i]); - } - else if (i < patternElements.length - 1 || !(e.kind === SyntaxKind.BindingElement && (e).dotDotDotToken || e.kind === SyntaxKind.SpreadElement)) { - if (e.kind !== SyntaxKind.OmittedExpression) { - error(e, Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, UnionReduction.Subtype); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes: Type[], contextualType: Type | undefined, hasRestElement: boolean, elementCount = elementTypes.length) { + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + const minLength = elementCount - (hasRestElement ? 1 : 0); + const pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === SyntaxKind.ArrayBindingPattern || pattern.kind === SyntaxKind.ArrayLiteralExpression)) { + const patternElements = (pattern).elements; + for (let i = elementCount; i < patternElements.length; i++) { + const e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push((contextualType).typeArguments![i]); + } + else if (i < patternElements.length - 1 || !(e.kind === SyntaxKind.BindingElement && (e).dotDotDotToken || e.kind === SyntaxKind.SpreadElement)) { + if (e.kind !== SyntaxKind.OmittedExpression) { + error(e, Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } + function getArrayLiteralType(elementTypes: Type[], unionReduction = UnionReduction.Literal) { return createArrayType(elementTypes.length ? getUnionType(elementTypes, unionReduction) : @@ -17027,9 +17393,9 @@ namespace ts { const contextualType = getApparentTypeOfContextualType(node); const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression); - const isInJSFile = isInJavaScriptFile(node) && !isInJsonFile(node); + const isInJavascript = isInJSFile(node) && !isInJsonFile(node); const enumTag = getJSDocEnumTag(node); - const isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + const isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; let typeFlags: TypeFlags = 0; let patternWithComputedProperties = false; let hasComputedStringProperty = false; @@ -17048,7 +17414,7 @@ namespace ts { let type = memberDecl.kind === SyntaxKind.PropertyAssignment ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { const jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -17207,7 +17573,7 @@ namespace ts { } function checkJsxSelfClosingElementDeferred(node: JsxSelfClosingElement) { - checkJsxOpeningLikeElementOrOpeningFragment(node, CheckMode.Normal); + checkJsxOpeningLikeElementOrOpeningFragment(node); } function checkJsxSelfClosingElement(node: JsxSelfClosingElement, _checkMode: CheckMode | undefined): Type { @@ -17217,7 +17583,7 @@ namespace ts { function checkJsxElementDeferred(node: JsxElement) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, CheckMode.Normal); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { @@ -17226,6 +17592,8 @@ namespace ts { else { checkExpression(node.closingElement.tagName); } + + checkJsxChildren(node); } function checkJsxElement(node: JsxElement, _checkMode: CheckMode | undefined): Type { @@ -17234,8 +17602,8 @@ namespace ts { return getJsxElementTypeAt(node) || anyType; } - function checkJsxFragment(node: JsxFragment, checkMode: CheckMode | undefined): Type { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); + function checkJsxFragment(node: JsxFragment): Type { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); if (compilerOptions.jsx === JsxEmit.React && (compilerOptions.jsxFactory || getSourceFileOfNode(node).pragmas.has("jsx"))) { error(node, compilerOptions.jsxFactory @@ -17243,6 +17611,7 @@ namespace ts { : Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } + checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } @@ -17283,12 +17652,14 @@ namespace ts { let hasSpreadAnyType = false; let typeToIntersect: Type | undefined; let explicitlySpecifyChildrenAttribute = false; + let propagatingFlags: TypeFlags = 0; const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (const attributeDecl of attributes.properties) { const member = attributeDecl.symbol; if (isJsxAttribute(attributeDecl)) { const exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & TypeFlags.PropagatingFlags); const attributeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; @@ -17306,7 +17677,7 @@ namespace ts { else { Debug.assert(attributeDecl.kind === SyntaxKind.JsxSpreadAttribute); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); attributesTable = createSymbolTable(); } const exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -17314,7 +17685,7 @@ namespace ts { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, exprType, attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -17324,7 +17695,7 @@ namespace ts { if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); } } @@ -17342,15 +17713,17 @@ namespace ts { error(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + const contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + const childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process const childrenPropSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); const childPropMap = createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), - attributes.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); } } @@ -17370,7 +17743,8 @@ namespace ts { */ function createJsxAttributesType() { const result = createAnonymousType(attributes.symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= TypeFlags.ContainsObjectLiteral; + const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; + result.flags |= (propagatingFlags |= TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag); result.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.JsxAttributes; return result; } @@ -17449,57 +17823,6 @@ namespace ts { return links.resolvedSymbol; } - function instantiateJsxSignatures(node: JsxOpeningLikeElement, signatures: ReadonlyArray) { - const instantiatedSignatures = []; - let candidateForTypeArgumentError: Signature | undefined; - let hasTypeArgumentError: boolean = !!node.typeArguments; - for (const signature of signatures) { - if (signature.typeParameters) { - const isJavascript = isInJavaScriptFile(node); - const typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); - if (typeArgumentInstantiated) { - hasTypeArgumentError = false; - instantiatedSignatures.push(typeArgumentInstantiated); - } - else { - if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - candidateForTypeArgumentError = signature; - } - const inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? InferenceFlags.AnyDefault : InferenceFlags.None); - const typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - } - else { - instantiatedSignatures.push(signature); - } - } - if (node.typeArguments && hasTypeArgumentError) { - if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); - } - // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine - else if (node.typeArguments.length !== 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); - } - } - return instantiatedSignatures; - } - - function getJsxSignatureTypeArgumentInstantiation(signature: Signature, node: JsxOpeningLikeElement, isJavascript: boolean, reportErrors = false) { - if (!node.typeArguments) { - return; - } - if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - return; - } - const args = checkTypeArguments(signature, node.typeArguments, reportErrors); - if (!args) { - return; - } - return getSignatureInstantiation(signature, args, isJavascript); - } - function getJsxNamespaceAt(location: Node | undefined): Symbol { const links = location && getNodeLinks(location); if (links && links.jsxNamespace) { @@ -17575,193 +17898,24 @@ namespace ts { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType: Type | undefined): Type | undefined { - if (!propsType) { - return undefined; - } - if (propsType.flags & TypeFlags.Intersection) { - const propsApparentType: Type[] = []; - for (const t of (propsType).types) { - propsApparentType.push(getApparentType(t)); - } - return getIntersectionType(propsApparentType); - } - return getApparentType(propsType); - } - - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return only attributes type of successfully resolved call signature. - * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) - * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement: JsxOpeningLikeElement, elementType: Type, elemInstanceType: Type, elementClassType?: Type): Type | undefined { - Debug.assert(!(elementType.flags & TypeFlags.Union)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - const jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - const callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); - if (callSignature !== unknownSignature) { - const callReturnType = callSignature && getReturnTypeOfSignature(callSignature); - let paramType = callReturnType && (callSignature!.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature!.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - // Intersect in JSX.IntrinsicAttributes if it exists - const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } - } - } - return undefined; - } - - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return all attributes type of resolved call signature including candidate signatures. - * This function assumes that the caller handled other possible element type of the JSX element. - * This function is a behavior used by language service when looking up completion in JSX element. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement: JsxOpeningLikeElement, elementType: Type, elemInstanceType: Type, elementClassType?: Type): Type | undefined { - Debug.assert(!(elementType.flags & TypeFlags.Union)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type - const jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. - const candidatesOutArray: Signature[] = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); - let result: Type | undefined; - let allMatchingAttributesType: Type | undefined; - for (const candidate of candidatesOutArray) { - const callReturnType = getReturnTypeOfSignature(candidate); - // TODO: GH#18217: callReturnType should always be defined... - let paramType: Type | undefined = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - let shouldBeCandidate = true; - for (const attribute of openingLikeElement.attributes.properties) { - if (isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType!, attribute.name.escapedText)) { // TODO: GH#18217 - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - - // If we can't find any matching, just return everything. - if (!result) { - result = allMatchingAttributesType; - } - // Intersect in JSX.IntrinsicAttributes if it exists - const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - - function getInstantiatedJsxSignatures(openingLikeElement: JsxOpeningLikeElement, elementType: Type, reportErrors?: boolean) { - const links = getNodeLinks(openingLikeElement); - if (!links.resolvedSignatures) { - links.resolvedSignatures = createMap(); - } - const cacheKey = "" + getTypeId(elementType); - if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { - return; - } - else if (links.resolvedSignatures.get(cacheKey)) { - return links.resolvedSignatures.get(cacheKey); - } - - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + function getUninstantiatedJsxSignaturesOfType(elementType: Type) { // Resolve the signatures, preferring constructor let signatures = getSignaturesOfType(elementType, SignatureKind.Construct); if (signatures.length === 0) { // No construct signatures, try call signatures signatures = getSignaturesOfType(elementType, SignatureKind.Call); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - if (reportErrors) { - error(openingLikeElement.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(openingLikeElement.tagName)); - } - return; - } } - - // Instantiate in context of source type - const results = instantiateJsxSignatures(openingLikeElement, signatures); - links.resolvedSignatures.set(cacheKey, results); - return results; + return signatures; } - /** - * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. - * For instance: - * declare function Foo(attr: { p1: string}): JSX.Element; - * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" - * - * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. - * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component - * - * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement - * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature - * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present - * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) - * @return attributes type if able to resolve the type of node - * anyType if there is no type ElementAttributesProperty or there is an error - * emptyObjectType if there is no "prop" in the element instance type - */ - function resolveCustomJsxElementAttributesType(openingLikeElement: JsxOpeningLikeElement, - shouldIncludeAllStatelessAttributesType: boolean, - elementType: Type, - elementClassType?: Type): Type { - - if (elementType.flags & TypeFlags.Union) { - const types = (elementType as UnionType).types; - return getUnionType(types.map(type => { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), UnionReduction.Subtype); - } - - // Shortcircuit any - if (isTypeAny(elementType)) { - return elementType; - } - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - else if (elementType.flags & TypeFlags.String) { - return anyType; - } - else if (elementType.flags & TypeFlags.StringLiteral) { + function getIntrinsicAttributesTypeFromStringLiteralType(type: StringLiteralType, location: Node): Type | undefined { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type // For example: // var CustomTag: "h1" = "h1"; // Hello World - const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); + const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); if (intrinsicElementsType !== errorType) { - const stringLiteralTypeName = (elementType).value; + const stringLiteralTypeName = type.value; const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -17770,37 +17924,26 @@ namespace ts { if (indexSignatureType) { return indexSignatureType; } - error(openingLikeElement, Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); + return undefined; } // If we need to report an error, we already done so here. So just return any to prevent any more error downstream return anyType; + } + + function checkJsxReturnAssignableToAppropriateBound(isSFC: boolean, elemInstanceType: Type, openingLikeElement: Node) { + if (isSFC) { + const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } } - - // Get the element instance type (the result of newing or invoking this tag) - - const instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); - if (!length(instantiatedSignatures)) { - return errorType; + else { + const classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } } - const elemInstanceType = getUnionType(instantiatedSignatures!.map(getReturnTypeOfSignature), UnionReduction.Subtype); - - // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. - // Otherwise get only attributes type from the signature picked by choose-overload logic. - const statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - - if (statelessAttributesType) { - return statelessAttributesType; - } - - // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - - const isJs = isInJavaScriptFile(openingLikeElement); - return getUnionType(instantiatedSignatures!.map(sig => getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true))); } /** @@ -17826,57 +17969,6 @@ namespace ts { return links.resolvedJsxElementAttributesType; } - /** - * Get attributes type of the given custom opening-like JSX element. - * This function is intended to be called from a caller that handles intrinsic JSX element already. - * @param node a custom JSX opening-like element - * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component - */ - function getCustomJsxElementAttributesType(node: JsxOpeningLikeElement, shouldIncludeAllStatelessAttributesType: boolean): Type { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); - } - - /** - * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. - * This function is called by language service (see: completions-tryGetGlobalSymbols). - * @param node a JSX opening-like element to get attributes type for - */ - function getAllAttributesTypeFromJsxOpeningLikeElement(node: JsxOpeningLikeElement): Type { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - // Because in language service, the given JSX opening-like element may be incomplete and therefore, - // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); - } - } - - /** - * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. - * @param node a JSXOpeningLikeElement node - * @return an attributes type of the given node - */ - function getAttributesTypeFromJsxOpeningLikeElement(node: JsxOpeningLikeElement): Type { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); - } - } - - /** - * Given a JSX attribute, returns the symbol for the corresponds property - * of the element attributes type. Will return unknownSymbol for attributes - * that have no matching element attributes type property. - */ - function getJsxAttributePropertySymbol(attrib: JsxAttribute): Symbol { - const attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent as JsxOpeningElement); - const prop = getPropertyOfType(attributesType, attrib.name.escapedText); - return prop || unknownSymbol; - } - function getJsxElementClassTypeAt(location: Node): Type | undefined { const type = getJsxType(JsxNames.ElementClass, location); if (type === errorType) return undefined; @@ -17915,7 +18007,7 @@ namespace ts { } } - function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment, checkMode: CheckMode | undefined) { + function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment) { const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { @@ -17940,10 +18032,8 @@ namespace ts { } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren((node as JsxOpeningFragment).parent); + const sig = getResolvedSignature(node as JsxOpeningLikeElement); + checkJsxReturnAssignableToAppropriateBound(isJsxStatelessFunctionReference(node as JsxOpeningLikeElement), getReturnTypeOfSignature(sig), node); } } @@ -17985,53 +18075,6 @@ namespace ts { return false; } - /** - * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. - * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" - * Check assignablity between given attributes property, "source attributes", and the "target attributes" - * @param openingLikeElement an opening-like JSX element to check its JSXAttributes - */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement: JsxOpeningLikeElement, checkMode: CheckMode | undefined) { - // The function involves following steps: - // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. - // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) - // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. - // 3. Check if the two are assignable to each other - - - // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. - const targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); - - // sourceAttributesType is a type of an attributes properties. - // i.e
- // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - const sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); - - // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties - const isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); - // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (const attribute of openingLikeElement.attributes.properties) { - if (!isJsxAttribute(attribute)) { - continue; - } - const attrName = attribute.name; - const isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, idText(attrName), typeToString(targetAttributesType)); - // We break here so that errors won't be cascading - break; - } - } - } - else if (!isSourceAttributeTypeAssignableToTarget) { - checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); - } - } - function checkJsxExpression(node: JsxExpression, checkMode?: CheckMode) { if (node.expression) { const type = checkExpression(node.expression, checkMode); @@ -18057,10 +18100,10 @@ namespace ts { if (symbol.flags & SymbolFlags.Method || getCheckFlags(symbol) & CheckFlags.SyntheticMethod) { return true; } - if (isInJavaScriptFile(symbol.valueDeclaration)) { + if (isInJSFile(symbol.valueDeclaration)) { const parent = symbol.valueDeclaration.parent; return parent && isBinaryExpression(parent) && - getSpecialPropertyAssignmentKind(parent) === SpecialPropertyAssignmentKind.PrototypeProperty; + getAssignmentDeclarationKind(parent) === AssignmentDeclarationKind.PrototypeProperty; } } @@ -18111,7 +18154,7 @@ namespace ts { // Referencing abstract properties within their own constructors is not allowed if ((flags & ModifierFlags.Abstract) && isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)!); - if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name!)); // TODO: GH#18217 return false; } @@ -18298,6 +18341,12 @@ namespace ts { } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + isPropertyAccessExpression(prop.valueDeclaration) && + getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } const flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & TypeFlags.Undefined) && getFalsyFlags(flowType) & TypeFlags.Undefined) { error(right, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop!)); // TODO: GH#18217 @@ -18543,7 +18592,7 @@ namespace ts { const prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : isInJavaScriptFile(node) && (type.flags & TypeFlags.Union) !== 0 && (type).types.some(elementType => isValidPropertyAccessWithType(node, isSuper, propertyName, elementType)); + : isInJSFile(node) && (type.flags & TypeFlags.Union) !== 0 && (type).types.some(elementType => isValidPropertyAccessWithType(node, isSuper, propertyName, elementType)); } /** @@ -18625,13 +18674,6 @@ namespace ts { error(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - if (isTupleType(objectType) && !objectType.target.hasRestElement && isNumericLiteral(indexExpression)) { - const index = +indexExpression.text; - const maximumIndex = length(objectType.target.typeParameters); - if (index >= maximumIndex) { - error(indexExpression, Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex); - } - } return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } @@ -18678,9 +18720,8 @@ namespace ts { return true; } - function callLikeExpressionMayHaveTypeArguments(node: CallLikeExpression): node is CallExpression | NewExpression { - // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) - return isCallOrNewExpression(node); + function callLikeExpressionMayHaveTypeArguments(node: CallLikeExpression): node is CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement { + return isCallOrNewExpression(node) || isTaggedTemplateExpression(node) || isJsxOpeningLikeElement(node); } function resolveUntypedCall(node: CallLikeExpression): Signature { @@ -18693,6 +18734,9 @@ namespace ts { if (node.kind === SyntaxKind.TaggedTemplateExpression) { checkExpression(node.template); } + else if (isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } else if (node.kind !== SyntaxKind.Decorator) { forEach((node).arguments, argument => { checkExpression(argument); @@ -18769,13 +18813,10 @@ namespace ts { } function hasCorrectArity(node: CallLikeExpression, args: ReadonlyArray, signature: Signature, signatureHelpTrailingComma = false) { - if (isJsxOpeningLikeElement(node)) { - // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". - return true; - } - let argCount: number; let callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments + let effectiveParameterCount = getParameterCount(signature); + let effectiveMinimumArguments = getMinArgumentCount(signature); if (node.kind === SyntaxKind.TaggedTemplateExpression) { argCount = args.length; @@ -18797,6 +18838,15 @@ namespace ts { else if (node.kind === SyntaxKind.Decorator) { argCount = getDecoratorArgumentCount(node, signature); } + else if (isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked + } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' @@ -18817,12 +18867,13 @@ namespace ts { } // Too many arguments implies incorrect arity. - if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { return false; } // If the call is incomplete, we should skip the lower bound check. - const hasEnoughArguments = argCount >= getMinArgumentCount(signature); + // JSX signatures can have extra parameters provided by the library which we don't check + const hasEnoughArguments = argCount >= effectiveMinimumArguments; return callIsIncomplete || hasEnoughArguments; } @@ -18858,18 +18909,13 @@ namespace ts { if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), InferencePriority.ReturnType); } - return getSignatureInstantiation(signature, getInferredTypes(context), isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), isInJSFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature: Signature, node: JsxOpeningLikeElement, context: InferenceContext): Type[] { - // Skip context sensitive pass - const skipContextParamType = getTypeAtPosition(signature, 0); - const checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); - inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); + function inferJsxTypeArguments(node: JsxOpeningLikeElement, signature: Signature, excludeArgument: ReadonlyArray | undefined, context: InferenceContext): Type[] { + const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); - // Standard pass - const paramType = getTypeAtPosition(signature, 0); - const checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + const checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); @@ -18887,6 +18933,10 @@ namespace ts { } } + if (isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } + // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the @@ -18979,7 +19029,7 @@ namespace ts { } function checkTypeArguments(signature: Signature, typeArgumentNodes: ReadonlyArray, reportErrors: boolean, headMessage?: DiagnosticMessage): Type[] | undefined { - const isJavascript = isInJavaScriptFile(signature.declaration); + const isJavascript = isInJSFile(signature.declaration); const typeParameters = signature.typeParameters!; const typeArgumentTypes = fillMissingTypeArguments(map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); let mapper: TypeMapper | undefined; @@ -19006,6 +19056,14 @@ namespace ts { return typeArgumentTypes; } + function isJsxStatelessFunctionReference(node: JsxOpeningLikeElement) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return true; + } + const tagType = checkExpression(node.tagName); + return !length(getSignaturesOfType(getApparentType(tagType), SignatureKind.Construct)); + } + /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. * @param node a JSX opening-like element we are trying to figure its call signature @@ -19013,31 +19071,13 @@ namespace ts { * @param relation a relationship to check parameter and argument type * @param excludeArgument */ - function checkApplicableSignatureForJsxOpeningLikeElement(node: JsxOpeningLikeElement, signature: Signature, relation: Map) { - // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: - // 1. callIsIncomplete - // 2. attributes property has same number of properties as the parameter object type. - // We can figure that out by resolving attributes property and check number of properties in the resolved type - // If the call has correct arity, we will then check if the argument type and parameter type is assignable - - const callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete - if (callIsIncomplete) { - return true; - } - - const headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + function checkApplicableSignatureForJsxOpeningLikeElement(node: JsxOpeningLikeElement, signature: Signature, relation: Map, reportErrors: boolean) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, // can be specified by users through attributes property. - const paramType = getTypeAtPosition(signature, 0); + const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); const attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); - const argProperties = getPropertiesOfType(attributesType); - for (const arg of argProperties) { - if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } function checkApplicableSignature( @@ -19048,7 +19088,7 @@ namespace ts { excludeArgument: boolean[] | undefined, reportErrors: boolean) { if (isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, reportErrors); } const thisType = getThisTypeOfSignature(signature); if (thisType && thisType !== voidType && node.kind !== SyntaxKind.NewExpression) { @@ -19126,7 +19166,7 @@ namespace ts { return getEffectiveDecoratorArguments(node); } if (isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : emptyArray; + return node.attributes.properties.length > 0 || (isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : emptyArray; } const args = node.arguments || emptyArray; const length = args.length; @@ -19215,12 +19255,16 @@ namespace ts { let aboveArgCount = Number.POSITIVE_INFINITY; let argCount = args.length; + let closestSignature: Signature | undefined; for (const sig of signatures) { const minCount = getMinArgumentCount(sig); const maxCount = getParameterCount(sig); if (minCount < argCount && minCount > belowArgCount) belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } @@ -19233,16 +19277,29 @@ namespace ts { argCount--; } + let related: DiagnosticWithLocation | undefined; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + const paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = createDiagnosticForNode( + paramDecl, + isBindingPattern(paramDecl.name) ? Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : Diagnostics.An_argument_for_0_was_not_provided, + !paramDecl.name ? argCount : !isBindingPattern(paramDecl.name) ? idText(getFirstIdentifier(paramDecl.name)) : undefined + ); + } + } if (hasRestParameter || hasSpreadArgument) { const error = hasRestParameter && hasSpreadArgument ? Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : Diagnostics.Expected_0_arguments_but_got_1_or_more; - return createDiagnosticForNode(node, error, paramRange, argCount); + const diagnostic = createDiagnosticForNode(node, error, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } if (min < argCount && argCount < max) { return createDiagnosticForNode(node, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return createDiagnosticForNode(node, Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + const diagnostic = createDiagnosticForNode(node, Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node: Node, signatures: ReadonlyArray, typeArguments: NodeArray) { @@ -19260,6 +19317,7 @@ namespace ts { const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; const isDecorator = node.kind === SyntaxKind.Decorator; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); + const reportErrors = !candidatesOutArray; let typeArguments: NodeArray | undefined; @@ -19276,7 +19334,9 @@ namespace ts { // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - diagnostics.add(createDiagnosticForNode(node, Diagnostics.Call_target_does_not_contain_any_signatures)); + if (reportErrors) { + diagnostics.add(createDiagnosticForNode(node, Diagnostics.Call_target_does_not_contain_any_signatures)); + } return resolveErrorCall(node); } @@ -19352,34 +19412,32 @@ namespace ts { // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, // skip the checkApplicableSignature check. - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". - return candidateForArgumentError; + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); - } - else if (candidateForArgumentArityError) { - diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); - } - else if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, (node as CallExpression | TaggedTemplateExpression).typeArguments!, /*reportErrors*/ true, fallbackError); - } - else { - const signaturesWithCorrectTypeArgumentArity = filter(signatures, s => hasCorrectTypeArgumentArity(s, typeArguments)); - if (signaturesWithCorrectTypeArgumentArity.length === 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments!)); + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); } - else if (!isDecorator) { - diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, (node as CallExpression | TaggedTemplateExpression | JsxOpeningLikeElement).typeArguments!, /*reportErrors*/ true, fallbackError); } - else if (fallbackError) { - diagnostics.add(createDiagnosticForNode(node, fallbackError)); + else { + const signaturesWithCorrectTypeArgumentArity = filter(signatures, s => hasCorrectTypeArgumentArity(s, typeArguments)); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments!)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(createDiagnosticForNode(node, fallbackError)); + } } } @@ -19421,10 +19479,10 @@ namespace ts { } } else { - inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ isInJavaScriptFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ isInJSFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJavaScriptFile(candidate.declaration)); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration)); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -19436,7 +19494,10 @@ namespace ts { checkCandidate = candidate; } if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = checkCandidate; + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } continue; } if (excludeArgument) { @@ -19446,10 +19507,13 @@ namespace ts { excludeArgument = undefined; if (inferenceContext) { const typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJavaScriptFile(candidate.declaration)); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration)); } if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = checkCandidate; + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } continue; } } @@ -19556,7 +19620,7 @@ namespace ts { const typeArgumentNodes: ReadonlyArray | undefined = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; const instantiated = typeArgumentNodes - ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJavaScriptFile(node))) + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJSFile(node))) : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); candidates[bestIndex] = instantiated; return instantiated; @@ -19574,7 +19638,7 @@ namespace ts { } function inferSignatureInstantiationForOverloadFailure(node: CallLikeExpression, typeParameters: ReadonlyArray, candidate: Signature, args: ReadonlyArray): Signature { - const inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ isInJavaScriptFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); + const inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ isInJSFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); const typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); return createSignatureInstantiation(candidate, typeArgumentTypes); } @@ -19641,12 +19705,12 @@ namespace ts { // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -19658,16 +19722,23 @@ namespace ts { // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, SignatureKind.Call); + let relatedInformation: DiagnosticRelatedInformation | undefined; + if (node.arguments.length === 1 && isTypeAssertion(first(node.arguments))) { + const text = getSourceFileOfNode(node).text; + if (isLineBreak(text.charCodeAt(skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = createDiagnosticForNode(node.expression, Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, SignatureKind.Call, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(sig => isInJavaScriptFile(sig.declaration) && !!getJSDocClassTag(sig.declaration!))) { + if (callSignatures.some(sig => isInJSFile(sig.declaration) && !!getJSDocClassTag(sig.declaration!))) { error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -19749,7 +19820,7 @@ namespace ts { if (callSignatures.length) { const signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); if (!noImplicitAny) { - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } if (getThisTypeOfSignature(signature) === voidType) { @@ -19832,11 +19903,12 @@ namespace ts { return true; } - function invocationError(node: Node, apparentType: Type, kind: SignatureKind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === SignatureKind.Call - ? Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature - , typeToString(apparentType))); + function invocationError(node: Node, apparentType: Type, kind: SignatureKind, relatedInformation?: DiagnosticRelatedInformation) { + const diagnostic = error(node, (kind === SignatureKind.Call ? + Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature + ), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType: Type, kind: SignatureKind, diagnostic: Diagnostic) { @@ -19866,9 +19938,9 @@ namespace ts { } const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length; - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } @@ -19916,8 +19988,8 @@ namespace ts { } const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } @@ -19940,6 +20012,74 @@ namespace ts { return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } + function createSignatureForJSXIntrinsic(node: JsxOpeningLikeElement, result: Type): Signature { + const namespace = getJsxNamespaceAt(node); + const exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + const typeSymbol = exports && getSymbol(exports, JsxNames.Element, SymbolFlags.Type); + const returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, SymbolFlags.Type, node); + const declaration = createFunctionTypeNode(/*typeParameters*/ undefined, + [createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], + returnNode ? createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : createKeywordTypeNode(SyntaxKind.AnyKeyword) + ); + const parameterSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, "props" as __String); + parameterSymbol.type = result; + return createSignature( + declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, + [parameterSymbol], + typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, + 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false + ); + } + + function resolveJsxOpeningLikeElement(node: JsxOpeningLikeElement, candidatesOutArray: Signature[] | undefined, isForSignatureHelp: boolean): Signature { + if (isJsxIntrinsicIdentifier(node.tagName)) { + const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + const fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + const exprTypes = checkExpression(node.tagName); + const apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + + if (exprTypes.flags & TypeFlags.StringLiteral) { + const intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes as StringLiteralType, node); + if (!intrinsicType) { + error(node, Diagnostics.Property_0_does_not_exist_on_type_1, (exprTypes as StringLiteralType).value, "JSX." + JsxNames.IntrinsicElements); + return resolveUntypedCall(node); + } + else { + const fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes); + return fakeSignature; + } + } + + const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + if (exprTypes.flags & TypeFlags.String || isUntypedFunctionCall(exprTypes, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + + const signatures = getUninstantiatedJsxSignaturesOfType(apparentType); + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } + /** * Sometimes, we have a decorator that could accept zero arguments, * but is receiving too many arguments as part of the decorator invocation. @@ -19952,26 +20092,6 @@ namespace ts { signature.parameters.length < getDecoratorArgumentCount(decorator, signature)); } - /** - * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. - * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName - * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) - * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. - * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function - * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement: JsxOpeningLikeElement, elementType: Type, candidatesOutArray: Signature[] | undefined, isForSignatureHelp: boolean): Signature | undefined { - Debug.assert(!(elementType.flags & TypeFlags.Union)); - const callSignatures = elementType && getSignaturesOfType(elementType, SignatureKind.Call); - if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); - } - - return undefined; - } - function resolveSignature(node: CallLikeExpression, candidatesOutArray: Signature[] | undefined, isForSignatureHelp: boolean): Signature { switch (node.kind) { case SyntaxKind.CallExpression: @@ -19984,19 +20104,7 @@ namespace ts { return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: - // This code-path is called by language service - const exprTypes = checkExpression(node.tagName); - return forEachType(exprTypes, exprType => { - const sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); - if (sfcResult && sfcResult !== unknownSignature) { - return sfcResult; - } - const sigs = getInstantiatedJsxSignatures(node, exprType); - if (candidatesOutArray && length(sigs)) { - candidatesOutArray.push(...sigs!); - } - return length(sigs) ? sigs![0] : unknownSignature; - }) || unknownSignature; + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); } throw Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -20031,38 +20139,40 @@ namespace ts { * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node: Declaration | undefined): boolean { - if (node && isInJavaScriptFile(node)) { + function isJSConstructor(node: Declaration | undefined): boolean { + if (!node || !isInJSFile(node)) { + return false; + } + const func = isFunctionDeclaration(node) || isFunctionExpression(node) ? node : + isVariableDeclaration(node) && node.initializer && isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - const symbol = isFunctionDeclaration(node) || isFunctionExpression(node) ? getSymbolOfNode(node) : - isVariableDeclaration(node) && node.initializer && isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; - + const symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } - return false; } - function isJavascriptConstructorType(type: Type) { + function isJSConstructorType(type: Type) { if (type.flags & TypeFlags.Object) { const resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol: Symbol): Type | undefined { + function getJSClassType(symbol: Symbol): Type | undefined { let inferred: Type | undefined; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } const assigned = getAssignedClassType(symbol); const valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -20070,21 +20180,18 @@ namespace ts { assigned || inferred; } - function getAssignedClassType(symbol: Symbol) { + function getAssignedClassType(symbol: Symbol): Type | undefined { const decl = symbol.valueDeclaration; const assignmentSymbol = decl && decl.parent && (isFunctionDeclaration(decl) && getSymbolOfNode(decl) || isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - const prototype = forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + const prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype" as __String); + const init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node: Node) { + function getAssignedJSPrototype(node: Node) { if (!node.parent) { return false; } @@ -20145,7 +20252,7 @@ namespace ts { if (!funcSymbol && node.expression.kind === SyntaxKind.Identifier) { funcSymbol = getResolvedSymbol(node.expression as Identifier); } - const type = funcSymbol && getJavascriptClassType(funcSymbol); + const type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -20157,7 +20264,7 @@ namespace ts { } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments![0] as StringLiteral); } @@ -20168,8 +20275,8 @@ namespace ts { return getESSymbolLikeTypeForNode(walkUpParenthesizedExpressions(node.parent)); } let jsAssignmentType: Type | undefined; - if (isInJavaScriptFile(node)) { - const decl = getDeclarationOfJSInitializer(node); + if (isInJSFile(node)) { + const decl = getDeclarationOfExpando(node); if (decl) { const jsSymbol = getSymbolOfNode(decl); if (jsSymbol && hasEntries(jsSymbol.exports)) { @@ -20558,6 +20665,18 @@ namespace ts { return emptyObjectType; } + function createPromiseLikeType(promisedType: Type): Type { + // creates a `PromiseLike` type where `T` is the promisedType argument + const globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + + return emptyObjectType; + } + function createPromiseReturnType(func: FunctionLikeDeclaration | ImportCall, promisedType: Type) { const promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -20794,7 +20913,7 @@ namespace ts { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(t => t.symbol === func.symbol))) { + !(isJSConstructor(func) && aggregatedTypes.some(t => t.symbol === func.symbol))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined pushIfUnique(aggregatedTypes, undefinedType); } @@ -20870,6 +20989,7 @@ namespace ts { function checkFunctionExpressionOrObjectLiteralMethod(node: FunctionExpression | MethodDeclaration, checkMode?: CheckMode): Type { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === CheckMode.SkipContextSensitive && isContextSensitive(node)) { @@ -20927,7 +21047,6 @@ namespace ts { } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } @@ -21330,7 +21449,7 @@ namespace ts { if (element.kind !== SyntaxKind.SpreadElement) { const propName = "" + elementIndex as __String; const type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -21356,8 +21475,8 @@ namespace ts { } else { checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - const type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + const type = everyType(sourceType, isTupleType) ? + mapType(sourceType, t => sliceTupleType(t, elementIndex)) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -21481,7 +21600,7 @@ namespace ts { } function checkBinaryExpression(node: BinaryExpression, checkMode?: CheckMode) { - if (isInJavaScriptFile(node) && getAssignedJavascriptInitializer(node)) { + if (isInJSFile(node) && getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -21629,9 +21748,9 @@ namespace ts { getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], UnionReduction.Subtype) : leftType; case SyntaxKind.EqualsToken: - const special = isBinaryExpression(left.parent) ? getSpecialPropertyAssignmentKind(left.parent) : SpecialPropertyAssignmentKind.None; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : AssignmentDeclarationKind.None; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -21648,8 +21767,8 @@ namespace ts { return Debug.fail(); } - function checkSpecialAssignment(special: SpecialPropertyAssignmentKind, right: Expression) { - if (special === SpecialPropertyAssignmentKind.ModuleExports) { + function checkAssignmentDeclaration(kind: AssignmentDeclarationKind, right: Expression) { + if (kind === AssignmentDeclarationKind.ModuleExports) { const rightType = checkExpression(right, checkMode); for (const prop of getPropertiesOfObjectType(rightType)) { const propType = getTypeOfSymbol(prop); @@ -21716,17 +21835,17 @@ namespace ts { } } - function isJSSpecialPropertyAssignment(special: SpecialPropertyAssignmentKind) { - switch (special) { - case SpecialPropertyAssignmentKind.ModuleExports: + function isAssignmentDeclaration(kind: AssignmentDeclarationKind) { + switch (kind) { + case AssignmentDeclarationKind.ModuleExports: return true; - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.Prototype: - case SpecialPropertyAssignmentKind.PrototypeProperty: - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.Prototype: + case AssignmentDeclarationKind.PrototypeProperty: + case AssignmentDeclarationKind.ThisProperty: const symbol = getSymbolOfNode(left); - const init = getAssignedJavascriptInitializer(right); + const init = getAssignedExpandoInitializer(right); return init && isObjectLiteralExpression(init) && symbol && hasEntries(symbol.exports); default: @@ -21854,7 +21973,7 @@ namespace ts { } function getContextNode(node: Expression): Node { - if (node.kind === SyntaxKind.JsxAttributes) { + if (node.kind === SyntaxKind.JsxAttributes && !isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -21902,17 +22021,13 @@ namespace ts { const widened = getCombinedNodeFlags(declaration) & NodeFlags.Const || isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (isInJavaScriptFile(declaration)) { + if (isInJSFile(declaration)) { if (widened.flags & TypeFlags.Nullable) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -21945,11 +22060,11 @@ namespace ts { return false; } - function checkExpressionForMutableLocation(node: Expression, checkMode: CheckMode | undefined, contextualType?: Type): Type { + function checkExpressionForMutableLocation(node: Expression, checkMode: CheckMode | undefined, contextualType?: Type, forceTuple?: boolean): Type { if (arguments.length === 2) { contextualType = getContextualType(node); } - const type = checkExpression(node, checkMode); + const type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -22049,13 +22164,13 @@ namespace ts { // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node: Expression | QualifiedName, checkMode?: CheckMode): Type { + function checkExpression(node: Expression | QualifiedName, checkMode?: CheckMode, forceTuple?: boolean): Type { let type: Type; if (node.kind === SyntaxKind.QualifiedName) { type = checkQualifiedName(node); } else { - const uninstantiatedType = checkExpressionWorker(node, checkMode); + const uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } @@ -22078,14 +22193,14 @@ namespace ts { } function checkParenthesizedExpression(node: ParenthesizedExpression, checkMode?: CheckMode): Type { - const tag = isInJavaScriptFile(node) ? getJSDocTypeTag(node) : undefined; + const tag = isInJSFile(node) ? getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression!.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node: Expression, checkMode: CheckMode | undefined): Type { + function checkExpressionWorker(node: Expression, checkMode: CheckMode | undefined, forceTuple?: boolean): Type { switch (node.kind) { case SyntaxKind.Identifier: return checkIdentifier(node); @@ -22110,7 +22225,7 @@ namespace ts { case SyntaxKind.RegularExpressionLiteral: return globalRegExpType; case SyntaxKind.ArrayLiteralExpression: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case SyntaxKind.ObjectLiteralExpression: return checkObjectLiteral(node, checkMode); case SyntaxKind.PropertyAccessExpression: @@ -22171,7 +22286,7 @@ namespace ts { case SyntaxKind.JsxSelfClosingElement: return checkJsxSelfClosingElement(node, checkMode); case SyntaxKind.JsxFragment: - return checkJsxFragment(node, checkMode); + return checkJsxFragment(node); case SyntaxKind.JsxAttributes: return checkJsxAttributes(node, checkMode); case SyntaxKind.JsxOpeningElement: @@ -22755,7 +22870,7 @@ namespace ts { function getEffectiveTypeArguments(node: TypeReferenceNode | ExpressionWithTypeArguments, typeParameters: ReadonlyArray): Type[] { return fillMissingTypeArguments(map(node.typeArguments!, getTypeFromTypeNode), typeParameters, - getMinTypeArgumentCount(typeParameters), isInJavaScriptFile(node)); + getMinTypeArgumentCount(typeParameters), isInJSFile(node)); } function checkTypeArgumentConstraints(node: TypeReferenceNode | ExpressionWithTypeArguments, typeParameters: ReadonlyArray): boolean { @@ -22793,7 +22908,7 @@ namespace ts { function checkTypeReferenceNode(node: TypeReferenceNode | ExpressionWithTypeArguments) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === SyntaxKind.TypeReference && node.typeName.jsdocDotPos !== undefined && !isInJavaScriptFile(node) && !isInJSDoc(node)) { + if (node.kind === SyntaxKind.TypeReference && node.typeName.jsdocDotPos !== undefined && !isInJSFile(node) && !isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } const type = getTypeFromTypeReference(node); @@ -22903,8 +23018,8 @@ namespace ts { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } const type = getTypeFromMappedTypeNode(node); @@ -23928,8 +24043,8 @@ namespace ts { if (produceDiagnostics && !getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & FunctionFlags.Generator && nodeIsPresent(body)) { @@ -23941,7 +24056,7 @@ namespace ts { } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { const typeTag = getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -24598,7 +24713,7 @@ namespace ts { // Don't validate for-in initializer as it is already an error const initializer = getEffectiveInitializer(node); if (initializer) { - const isJSObjectLiteralInitializer = isInJavaScriptFile(node) && + const isJSObjectLiteralInitializer = isInJSFile(node) && isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && hasEntries(symbol.exports); @@ -24615,7 +24730,7 @@ namespace ts { if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & SymbolFlags.JSContainer)) { + !(symbol.flags & SymbolFlags.Assignment)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -25043,14 +25158,18 @@ namespace ts { if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = (type).typeArguments![0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType((type).typeArguments![0]) + : typeAsIterable.iteratedTypeOfIterable = (type).typeArguments![0]; } } @@ -25081,9 +25200,11 @@ namespace ts { : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } @@ -25695,8 +25816,11 @@ namespace ts { if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, - Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, + Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & TypeFlags.TypeVariable && !isMixinConstructorType(staticType)) { error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -25708,7 +25832,7 @@ namespace ts { // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (forEach(constructors, sig => !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType)) { + if (forEach(constructors, sig => !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType)) { error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -25959,6 +26083,8 @@ namespace ts { function isPropertyInitializedInConstructor(propName: Identifier, propType: Type, constructor: ConstructorDeclaration) { const reference = createPropertyAccess(createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; const flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & TypeFlags.Undefined); @@ -26696,7 +26822,7 @@ namespace ts { const exportEqualsSymbol = moduleSymbol.exports!.get("export=" as __String); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) { error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -26746,7 +26872,7 @@ namespace ts { return; } - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { forEach((node as JSDocContainer).jsDoc, ({ tags }) => forEach(tags, checkSourceElement)); } @@ -26913,7 +27039,7 @@ namespace ts { } function checkJSDocTypeIsInJsFile(node: Node): void { - if (!isInJavaScriptFile(node)) { + if (!isInJSFile(node)) { grammarErrorOnNode(node, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -26992,14 +27118,21 @@ namespace ts { // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node: Node) { - if (deferredNodes) { + const enclosingFile = getSourceFileOfNode(node); + const links = getNodeLinks(enclosingFile); + if (!(links.flags & NodeCheckFlags.TypeChecked)) { + links.deferredNodes = links.deferredNodes || createMap(); const id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes!.forEach(node => { + function checkDeferredNodes(context: SourceFile) { + const links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(node => { switch (node.kind) { case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: @@ -27060,10 +27193,9 @@ namespace ts { clear(potentialThisCollisions); clear(potentialNewTargetCollisions); - deferredNodes = createMap(); forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); @@ -27077,8 +27209,6 @@ namespace ts { }); } - deferredNodes = undefined; - if (isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -27297,12 +27427,12 @@ namespace ts { return result; } - function isNodeUsedDuringClassInitialization(node: Node, classDeclaration: ClassLikeDeclaration) { + function isNodeUsedDuringClassInitialization(node: Node) { return !!findAncestor(node, element => { - if ((isConstructorDeclaration(element) && nodeIsPresent(element.body) || isPropertyDeclaration(element)) && element.parent === classDeclaration) { + if (isConstructorDeclaration(element) && nodeIsPresent(element.body) || isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || isFunctionLikeDeclaration(element)) { + else if (isClassLike(element) || isFunctionLikeDeclaration(element)) { return "quit"; } @@ -27335,14 +27465,14 @@ namespace ts { } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName: EntityName | PropertyAccessExpression) { - const specialPropertyAssignmentKind = getSpecialPropertyAssignmentKind(entityName.parent.parent as BinaryExpression); + const specialPropertyAssignmentKind = getAssignmentDeclarationKind(entityName.parent.parent as BinaryExpression); switch (specialPropertyAssignmentKind) { - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.PrototypeProperty: return getSymbolOfNode(entityName.parent); - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.ModuleExports: - case SpecialPropertyAssignmentKind.Property: + case AssignmentDeclarationKind.ThisProperty: + case AssignmentDeclarationKind.ModuleExports: + case AssignmentDeclarationKind.Property: return getSymbolOfNode(entityName.parent.parent); } } @@ -27364,7 +27494,7 @@ namespace ts { return getSymbolOfNode(entityName.parent); } - if (isInJavaScriptFile(entityName) && + if (isInJSFile(entityName) && entityName.parent.kind === SyntaxKind.PropertyAccessExpression && entityName.parent === (entityName.parent.parent as BinaryExpression).left) { // Check if this is a special property assignment @@ -27429,7 +27559,7 @@ namespace ts { } if (entityName.parent.kind === SyntaxKind.TypeParameter && entityName.parent.parent.kind === SyntaxKind.JSDocTemplateTag) { - Debug.assert(!isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + Debug.assert(!isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. const typeParameter = getTypeParameterFromJsDoc(entityName.parent as TypeParameterDeclaration & { parent: JSDocTemplateTag }); return typeParameter && typeParameter.symbol; } @@ -27467,9 +27597,6 @@ namespace ts { const meaning = entityName.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === SyntaxKind.JsxAttribute) { - return getJsxAttributePropertySymbol(entityName.parent); - } if (entityName.parent.kind === SyntaxKind.TypePredicate) { return resolveEntityName(entityName, /*meaning*/ SymbolFlags.FunctionScopedVariable); @@ -27556,7 +27683,7 @@ namespace ts { // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration) && (node.parent).moduleSpecifier === node) || - ((isInJavaScriptFile(node) && isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || isImportCall(node.parent)) || + ((isInJSFile(node) && isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || isImportCall(node.parent)) || (isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) ) { return resolveExternalModuleName(node, node); @@ -27605,24 +27732,20 @@ namespace ts { return errorType; } + const classDecl = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + const classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (isPartOfTypeNode(node)) { const typeFromTypeNode = getTypeFromTypeNode(node); - - if (isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - return getTypeWithThisArgument(typeFromTypeNode, getTypeOfClassContainingHeritageClause(node).thisType); - } - - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl!.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - const classType = getTypeOfClassContainingHeritageClause(node); const baseType = firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -27664,10 +27787,6 @@ namespace ts { return errorType; } - function getTypeOfClassContainingHeritageClause(node: ExpressionWithTypeArguments): InterfaceType { - return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node.parent.parent)); - } - // Gets the type of object literal or array literal of destructuring assignment. // { a } from // for ( { a } of elems) { @@ -27756,8 +27875,11 @@ namespace ts { function getAugmentedPropertiesOfType(type: Type): Symbol[] { type = getApparentType(type); const propsByName = createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - forEach(getPropertiesOfType(globalFunctionType), p => { + const functionType = getSignaturesOfType(type, SignatureKind.Call).length ? globalCallableFunctionType : + getSignaturesOfType(type, SignatureKind.Construct).length ? globalNewableFunctionType : + undefined; + if (functionType) { + forEach(getPropertiesOfType(functionType), p => { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -28070,7 +28192,7 @@ namespace ts { hasModifier(parameter, ModifierFlags.ParameterPropertyModifier); } - function isJSContainerFunctionDeclaration(node: Declaration): boolean { + function isExpandoFunctionDeclaration(node: Declaration): boolean { const declaration = getParseTreeNode(node, isFunctionDeclaration); if (!declaration) { return false; @@ -28079,7 +28201,7 @@ namespace ts { if (!symbol || !(symbol.flags & SymbolFlags.Function)) { return false; } - return !!forEachEntry(getExportsOfSymbol(symbol), p => isPropertyAccessExpression(p.valueDeclaration)); + return !!forEachEntry(getExportsOfSymbol(symbol), p => p.flags & SymbolFlags.Value && isPropertyAccessExpression(p.valueDeclaration)); } function getPropertiesOfContainerFunction(node: Declaration): Symbol[] { @@ -28276,19 +28398,20 @@ namespace ts { function isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean { if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node)) { const type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & TypeFlags.StringOrNumberLiteral && type.flags & TypeFlags.FreshLiteral); + return !!(type.flags & TypeFlags.Literal && type.flags & TypeFlags.FreshLiteral); } return false; } - function literalTypeToNode(type: LiteralType, enclosing: Node): Expression { - const enumResult = type.flags & TypeFlags.EnumLiteral && nodeBuilder.symbolToExpression(type.symbol, SymbolFlags.Value, enclosing); - return enumResult || createLiteral(type.value); + function literalTypeToNode(type: FreshableType, enclosing: Node): Expression { + const enumResult = type.flags & TypeFlags.EnumLiteral ? nodeBuilder.symbolToExpression(type.symbol, SymbolFlags.Value, enclosing) + : type === trueType ? createTrue() : type === falseType && createFalse(); + return enumResult || createLiteral((type as LiteralType).value); } function createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration) { const type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type, node); + return literalTypeToNode(type, node); } function createResolver(): EmitResolver { @@ -28332,7 +28455,7 @@ namespace ts { isImplementationOfOverload, isRequiredInitializedParameter, isOptionalUninitializedParameterProperty, - isJSContainerFunctionDeclaration, + isExpandoFunctionDeclaration, getPropertiesOfContainerFunction, createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration, @@ -28375,7 +28498,12 @@ namespace ts { getAccessor }; }, - getSymbolOfExternalModuleSpecifier: moduleName => resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined) + getSymbolOfExternalModuleSpecifier: moduleName => resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined), + isBindingCapturedByNode: (node, decl) => { + const parseNode = getParseTreeNode(node); + const parseDecl = getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (isVariableDeclaration(parseDecl) || isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node: PropertyAccessEntityNameExpression) { @@ -28488,6 +28616,9 @@ namespace ts { if (!isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals!); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -28533,6 +28664,8 @@ namespace ts { globalArrayType = getGlobalType("Array" as __String, /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object" as __String, /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function" as __String, /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction" as __String, /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction" as __String, /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String" as __String, /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number" as __String, /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean" as __String, /*arity*/ 0, /*reportErrors*/ true); @@ -28560,38 +28693,33 @@ namespace ts { } } - amalgamatedDuplicates.forEach(({ firstFile, secondFile, firstFileInstances, secondFileInstances }) => { - const conflictingKeys = arrayFrom(firstFileInstances.keys()); + amalgamatedDuplicates.forEach(({ firstFile, secondFile, conflictingSymbols }) => { // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(({ isBlockScoped, firstFileLocations, secondFileLocations }, symbolName) => { + const message = isBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; + for (const node of firstFileLocations) { + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (const node of secondFileLocations) { + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + const list = arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo( + createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), + createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file) + )); + diagnostics.add(addRelatedInfo( + createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), + createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file) + )); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - const list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo( - createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), - createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file) - )); - diagnostics.add(addRelatedInfo( - createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), - createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file) - )); }); amalgamatedDuplicates = undefined; - - function addErrorsForDuplicates(secondFileInstances: Map<{ instances: Node[]; blockScoped: boolean; }>, firstFileInstances: Map<{ instances: Node[]; blockScoped: boolean; }>) { - secondFileInstances.forEach((locations, symbolName) => { - const firstFileEquivalent = firstFileInstances.get(symbolName)!; - const message = locations.blockScoped - ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(node => { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location: Node, helpers: ExternalEmitHelpers) { @@ -29660,7 +29788,7 @@ namespace ts { function checkAmbientInitializer(node: VariableDeclaration | PropertyDeclaration | PropertySignature) { if (node.initializer) { - const isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer)); + const isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === SyntaxKind.TrueKeyword || node.initializer.kind === SyntaxKind.FalseKeyword); const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node); if (isConstOrReadonly && !node.type) { if (isInvalidInitializer) { @@ -29835,10 +29963,11 @@ namespace ts { } function checkGrammarConstructorTypeParameters(node: ConstructorDeclaration) { - const jsdocTypeParameters = isInJavaScriptFile(node) && getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - const { pos, end } = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node; - return grammarErrorAtPos(node, pos, end - pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + const jsdocTypeParameters = isInJSFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined; + const range = node.typeParameters || jsdocTypeParameters && firstOrUndefined(jsdocTypeParameters); + if (range) { + const pos = range.pos === range.end ? range.pos : skipTrivia(getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index e4c4edcb4db..160debf72e6 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -62,7 +62,8 @@ namespace ts { /* @internal */ export const libMap = createMapFromEntries(libEntries); - const commonOptionsWithBuild: CommandLineOption[] = [ + /* @internal */ + export const commonOptionsWithBuild: CommandLineOption[] = [ { name: "help", shortName: "h", @@ -76,6 +77,14 @@ namespace ts { shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Watch_input_files, + }, { name: "preserveWatchOutput", type: "boolean", @@ -84,12 +93,23 @@ namespace ts { description: Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, }, { - name: "watch", - shortName: "w", + name: "listFiles", type: "boolean", - showInSimplifiedHelpView: true, - category: Diagnostics.Command_line_Options, - description: Diagnostics.Watch_input_files, + category: Diagnostics.Advanced_Options, + description: Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: Diagnostics.Advanced_Options, + description: Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + + { + name: "traceResolution", + type: "boolean", + category: Diagnostics.Advanced_Options, + description: Diagnostics.Enable_tracing_of_the_name_resolution_process }, ]; @@ -159,6 +179,8 @@ namespace ts { es2018: ScriptTarget.ES2018, esnext: ScriptTarget.ESNext, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: Diagnostics.VERSION, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, @@ -177,6 +199,7 @@ namespace ts { es2015: ModuleKind.ES2015, esnext: ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: Diagnostics.KIND, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, @@ -189,6 +212,7 @@ namespace ts { name: "lib", type: libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -196,6 +220,7 @@ namespace ts { { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, description: Diagnostics.Allow_javascript_files_to_be_compiled @@ -213,6 +238,7 @@ namespace ts { "react-native": JsxEmit.ReactNative, "react": JsxEmit.React }), + affectsSourceFile: true, paramType: Diagnostics.KIND, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, @@ -323,6 +349,7 @@ namespace ts { { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -331,6 +358,7 @@ namespace ts { { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -339,14 +367,24 @@ namespace ts { { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, description: Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Strict_Type_Checking_Options, + description: Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -355,6 +393,7 @@ namespace ts { { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -363,6 +402,7 @@ namespace ts { { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -397,6 +437,7 @@ namespace ts { { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: Diagnostics.Additional_Checks, @@ -410,6 +451,7 @@ namespace ts { node: ModuleResolutionKind.NodeJs, classic: ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: Diagnostics.STRATEGY, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -417,6 +459,7 @@ namespace ts { { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -426,6 +469,7 @@ namespace ts { // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -441,6 +485,7 @@ namespace ts { type: "string", isFilePath: true }, + affectsModuleResolution: true, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -452,6 +497,7 @@ namespace ts { type: "string", isFilePath: true }, + affectsModuleResolution: true, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -462,6 +508,7 @@ namespace ts { name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.Module_Resolution_Options, description: Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -549,30 +596,12 @@ namespace ts { category: Diagnostics.Advanced_Options, description: Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: Diagnostics.Advanced_Options, - description: Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: Diagnostics.Advanced_Options, description: Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: Diagnostics.Advanced_Options, - description: Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: Diagnostics.Advanced_Options, - description: Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", @@ -632,12 +661,14 @@ namespace ts { { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: Diagnostics.Advanced_Options, description: Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: Diagnostics.Advanced_Options, description: Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -650,6 +681,7 @@ namespace ts { { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: Diagnostics.Advanced_Options, description: Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -695,6 +727,7 @@ namespace ts { { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: Diagnostics.Advanced_Options, description: Diagnostics.Do_not_report_errors_on_unused_labels @@ -702,6 +735,7 @@ namespace ts { { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: Diagnostics.Advanced_Options, description: Diagnostics.Do_not_report_errors_on_unreachable_code @@ -729,6 +763,7 @@ namespace ts { { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: Diagnostics.Advanced_Options, description: Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -758,6 +793,18 @@ namespace ts { } ]; + /* @internal */ + export const semanticDiagnosticsOptionDeclarations: ReadonlyArray = + optionDeclarations.filter(option => !!option.affectsSemanticDiagnostics); + + /* @internal */ + export const moduleResolutionOptionDeclarations: ReadonlyArray = + optionDeclarations.filter(option => !!option.affectsModuleResolution); + + /* @internal */ + export const sourceFileAffectingCompilerOptions: ReadonlyArray = optionDeclarations.filter(option => + !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics); + /* @internal */ export const buildOpts: CommandLineOption[] = [ ...commonOptionsWithBuild, @@ -903,17 +950,27 @@ namespace ts { } } - export function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine { - const options: CompilerOptions = {}; + /* @internal */ + export interface OptionsBase { + [option: string]: CompilerOptionsValue | undefined; + } + + /** Tuple with error messages for 'unknown compiler option', 'option requires type' */ + type ParseCommandLineWorkerDiagnostics = [DiagnosticMessage, DiagnosticMessage]; + + function parseCommandLineWorker( + getOptionNameMap: () => OptionNameMap, + [unknownOptionDiagnostic, optionTypeMismatchDiagnostic]: ParseCommandLineWorkerDiagnostics, + commandLine: ReadonlyArray, + readFile?: (path: string) => string | undefined) { + const options = {} as OptionsBase; const fileNames: string[] = []; - const projectReferences: ProjectReference[] | undefined = undefined; const errors: Diagnostic[] = []; parseStrings(commandLine); return { options, fileNames, - projectReferences, errors }; @@ -926,7 +983,7 @@ namespace ts { parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === CharacterCodes.minus) { - const opt = getOptionFromName(s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1), /*allowShort*/ true); + const opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -934,7 +991,7 @@ namespace ts { else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { @@ -956,7 +1013,7 @@ namespace ts { i++; break; case "list": - const result = parseListTypeOption(opt, args[i], errors); + const result = parseListTypeOption(opt, args[i], errors); options[opt.name] = result || []; if (result) { i++; @@ -971,7 +1028,7 @@ namespace ts { } } else { - errors.push(createCompilerDiagnostic(Diagnostics.Unknown_compiler_option_0, s)); + errors.push(createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -1014,13 +1071,19 @@ namespace ts { } } + export function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine { + return parseCommandLineWorker(getOptionNameMap, [ + Diagnostics.Unknown_compiler_option_0, + Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } + /** @internal */ export function getOptionFromName(optionName: string, allowShort?: boolean): CommandLineOption | undefined { return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); } - /*@internal*/ - export function getOptionDeclarationFromName(getOptionNameMap: () => OptionNameMap, optionName: string, allowShort = false): CommandLineOption | undefined { + function getOptionDeclarationFromName(getOptionNameMap: () => OptionNameMap, optionName: string, allowShort = false): CommandLineOption | undefined { optionName = optionName.toLowerCase(); const { optionNameMap, shortOptionNames } = getOptionNameMap(); // Try to translate short option names to their full equivalents. @@ -1044,25 +1107,11 @@ namespace ts { export function parseBuildCommand(args: string[]): ParsedBuildCommand { let buildOptionNameMap: OptionNameMap | undefined; const returnBuildOptionNameMap = () => (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(buildOpts))); - - const buildOptions: BuildOptions = {}; - const projects: string[] = []; - let errors: Diagnostic[] | undefined; - for (const arg of args) { - if (arg.charCodeAt(0) === CharacterCodes.minus) { - const opt = getOptionDeclarationFromName(returnBuildOptionNameMap, arg.slice(arg.charCodeAt(1) === CharacterCodes.minus ? 2 : 1), /*allowShort*/ true); - if (opt) { - buildOptions[opt.name as keyof BuildOptions] = true; - } - else { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Unknown_build_option_0, arg)); - } - } - else { - // Not a flag, parse as filename - projects.push(arg); - } - } + const { options, fileNames: projects, errors } = parseCommandLineWorker(returnBuildOptionNameMap, [ + Diagnostics.Unknown_build_option_0, + Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args); + const buildOptions = options as BuildOptions; if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." @@ -1071,19 +1120,19 @@ namespace ts { // Nonsensical combinations if (buildOptions.clean && buildOptions.force) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); } if (buildOptions.clean && buildOptions.verbose) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); } if (buildOptions.clean && buildOptions.watch) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); } if (buildOptions.watch && buildOptions.dry) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); } - return { buildOptions, projects, errors: errors || emptyArray }; + return { buildOptions, projects, errors }; } function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string { @@ -1480,7 +1529,12 @@ namespace ts { elements: NodeArray, elementOption: CommandLineOption | undefined ): any[] | void { - return (returnValue ? elements.map : elements.forEach).call(elements, (element: Expression) => convertPropertyValueToJson(element, elementOption)); + if (!returnValue) { + return elements.forEach(element => convertPropertyValueToJson(element, elementOption)); + } + + // Filter out invalid values + return filter(elements.map(element => convertPropertyValueToJson(element, elementOption)), v => v !== undefined); } function convertPropertyValueToJson(valueExpression: Expression, option: CommandLineOption | undefined): any { @@ -1613,7 +1667,7 @@ namespace ts { return undefined; } else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption((optionDefinition).element); + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); } else { return (optionDefinition).type; @@ -1677,7 +1731,7 @@ namespace ts { case "object": return {}; default: - return (option as CommandLineOptionOfCustomType).type.keys().next().value; + return option.type.keys().next().value; } } @@ -1825,7 +1879,8 @@ namespace ts { const options = extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - const { fileNames, wildcardDirectories, spec, projectReferences } = getFileNames(); + let projectReferences: ProjectReference[] | undefined; + const { fileNames, wildcardDirectories, spec } = getFileNames(); return { options, fileNames, @@ -1843,8 +1898,22 @@ namespace ts { if (hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (isArray(raw.files)) { filesSpecs = >raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + const hasReferences = hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + const hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + const hasExtends = hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + const fileName = configFileName || "tsconfig.json"; + const diagnosticMessage = Diagnostics.The_files_list_in_config_file_0_is_empty; + const nodeValue = firstDefined(getTsConfigPropArray(sourceFile, "files"), property => property.initializer); + const error = nodeValue + ? createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -1885,19 +1954,18 @@ namespace ts { } const result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !hasProperty(raw, "files") && resolutionStack.length === 0 && !hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (isArray(raw.references)) { - const references: ProjectReference[] = []; for (const ref of raw.references) { if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -1905,7 +1973,6 @@ namespace ts { }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -1922,13 +1989,11 @@ namespace ts { } } - /*@internal*/ - export function isErrorNoInputFiles(error: Diagnostic) { + function isErrorNoInputFiles(error: Diagnostic) { return error.code === Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - /*@internal*/ - export function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }: ConfigFileSpecs, configFileName: string | undefined) { + function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }: ConfigFileSpecs, configFileName: string | undefined) { return createCompilerDiagnostic( Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", @@ -1936,6 +2001,27 @@ namespace ts { JSON.stringify(excludeSpecs || [])); } + function shouldReportNoInputFiles(result: ExpandResult, canJsonReportNoInutFiles: boolean, resolutionStack?: Path[]) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + + /*@internal*/ + export function canJsonReportNoInutFiles(raw: any) { + return !hasProperty(raw, "files") && !hasProperty(raw, "references"); + } + + /*@internal*/ + export function updateErrorForNoInputFiles(result: ExpandResult, configFileName: string, configFileSpecs: ConfigFileSpecs, configParseDiagnostics: Diagnostic[], canJsonReportNoInutFiles: boolean) { + const existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + filterMutate(configParseDiagnostics, error => !isErrorNoInputFiles(error)); + } + return existingErrors !== configParseDiagnostics.length; + } + interface ParsedTsconfig { raw: any; options?: CompilerOptions; @@ -1978,7 +2064,7 @@ namespace ts { if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - const extendedConfig = getExtendedConfig(sourceFile!, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); + const extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { const baseRaw = extendedConfig.raw; const raw = ownConfig.raw; @@ -2067,11 +2153,6 @@ namespace ts { createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0) ); return; - case "files": - if ((>value).length === 0) { - errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueNode, Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot(key: string, keyNode: PropertyName, _value: CompilerOptionsValue, _valueNode: Expression) { @@ -2081,6 +2162,7 @@ namespace ts { } }; const json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -2123,7 +2205,7 @@ namespace ts { } function getExtendedConfig( - sourceFile: TsConfigSourceFile, + sourceFile: TsConfigSourceFile | undefined, extendedConfigPath: string, host: ParseConfigHost, basePath: string, @@ -2132,7 +2214,7 @@ namespace ts { ): ParsedTsconfig | undefined { const extendedResult = readJsonConfigFile(extendedConfigPath, path => host.readFile(path)); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push(...extendedResult.parseDiagnostics); @@ -2142,8 +2224,8 @@ namespace ts { const extendedDirname = getDirectoryPath(extendedConfigPath); const extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { - sourceFile.extendedSourceFiles!.push(...extendedResult.extendedSourceFiles!); + if (sourceFile && extendedResult.extendedSourceFiles) { + sourceFile.extendedSourceFiles!.push(...extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -2256,7 +2338,7 @@ namespace ts { function normalizeOptionValue(option: CommandLineOption, basePath: string, value: any): CompilerOptionsValue { if (isNullOrUndefined(value)) return undefined; if (option.type === "list") { - const listOption = option; + const listOption = option; if (listOption.element.isFilePath || !isString(listOption.element.type)) { return filter(map(value, v => normalizeOptionValue(listOption.element, basePath, v)), v => !!v); } @@ -2398,7 +2480,7 @@ namespace ts { // new entries in these paths. const wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - const spec: ConfigFileSpecs = { filesSpecs, referencesSpecs: undefined, includeSpecs, excludeSpecs, validatedIncludeSpecs, validatedExcludeSpecs, wildcardDirectories }; + const spec: ConfigFileSpecs = { filesSpecs, includeSpecs, excludeSpecs, validatedIncludeSpecs, validatedExcludeSpecs, wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } @@ -2427,11 +2509,16 @@ namespace ts { // via wildcard, and to handle extension priority. const wildcardFileMap = createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + const wildCardJsonFileMap = createMap(); const { filesSpecs, validatedIncludeSpecs, validatedExcludeSpecs, wildcardDirectories } = spec; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. const supportedExtensions = getSupportedExtensions(options, extraFileExtensions); + const supportedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. @@ -2442,8 +2529,25 @@ namespace ts { } } + let jsonOnlyIncludeRegexes: ReadonlyArray | undefined; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (const file of host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined)) { + for (const file of host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined)) { + if (fileExtensionIs(file, Extension.Json)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + const includes = validatedIncludeSpecs.filter(s => endsWith(s, Extension.Json)); + const includeFilePatterns = map(getRegularExpressionsForWildcards(includes, basePath, "files"), pattern => `^${pattern}$`); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(pattern => getRegexFromPattern(pattern, host.useCaseSensitiveFileNames)) : emptyArray; + } + const includeIndex = findIndex(jsonOnlyIncludeRegexes, re => re.test(file)); + if (includeIndex !== -1) { + const key = keyMapper(file); + if (!literalFileMap.has(key) && !wildCardJsonFileMap.has(key)) { + wildCardJsonFileMap.set(key, file); + } + } + continue; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -2469,16 +2573,9 @@ namespace ts { const literalFiles = arrayFrom(literalFileMap.values()); const wildcardFiles = arrayFrom(wildcardFileMap.values()); - const projectReferences = spec.referencesSpecs && spec.referencesSpecs.map((r): ProjectReference => { - return { - ...r, - path: getNormalizedAbsolutePath(r.path, basePath) - }; - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences, + fileNames: literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories, spec }; @@ -2648,7 +2745,7 @@ namespace ts { case "boolean": return typeof value === "boolean" ? value : ""; case "list": - const elementType = (option as CommandLineOptionOfListType).element; + const elementType = option.element; return isArray(value) ? value.map(v => getOptionValueWithEmptyStrings(v, elementType)) : ""; default: return forEachEntry(option.type, (optionEnumValue, optionStringValue) => { diff --git a/src/compiler/comments.ts b/src/compiler/comments.ts index 7dfda66c965..485e3e04aad 100644 --- a/src/compiler/comments.ts +++ b/src/compiler/comments.ts @@ -220,7 +220,7 @@ namespace ts { } if (extendedDiagnostics) { - performance.mark("beginEmitBodyWithDetachedCommetns"); + performance.mark("beginEmitBodyWithDetachedComments"); } if (!skipTrailingComments) { @@ -231,7 +231,7 @@ namespace ts { } if (extendedDiagnostics) { - performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + performance.measure("commentTime", "beginEmitBodyWithDetachedComments"); } } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 7840c66e601..7e9813658f5 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1,7 +1,7 @@ namespace ts { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - export const versionMajorMinor = "3.1"; + export const versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ export const version = `${versionMajorMinor}.0-dev`; } @@ -65,6 +65,7 @@ namespace ts { /* @internal */ namespace ts { + export const emptyArray: never[] = [] as never[]; /** Create a MapLike with good performance. */ function createDictionaryObject(): MapLike { @@ -841,7 +842,7 @@ namespace ts { return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); } - export function arrayIsEqualTo(array1: ReadonlyArray | undefined, array2: ReadonlyArray | undefined, equalityComparer: (a: T, b: T) => boolean = equateValues): boolean { + export function arrayIsEqualTo(array1: ReadonlyArray | undefined, array2: ReadonlyArray | undefined, equalityComparer: (a: T, b: T, index: number) => boolean = equateValues): boolean { if (!array1 || !array2) { return array1 === array2; } @@ -851,7 +852,7 @@ namespace ts { } for (let i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1408,9 +1409,12 @@ namespace ts { /** * Tests whether a value is string */ - export function isString(text: any): text is string { + export function isString(text: unknown): text is string { return typeof text === "string"; } + export function isNumber(x: unknown): x is number { + return typeof x === "number"; + } export function tryCast(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut | undefined; export function tryCast(value: T, test: (value: T) => boolean): T | undefined; @@ -1533,6 +1537,7 @@ namespace ts { * Every function should be assignable to this, but this should not be assignable to every function. */ export type AnyFunction = (...args: never[]) => void; + export type AnyConstructor = new (...args: unknown[]) => unknown; export namespace Debug { export let currentAssertionLevel = AssertionLevel.None; @@ -1597,8 +1602,9 @@ namespace ts { return value; } - export function assertNever(member: never, message?: string, stackCrawlMark?: AnyFunction): never { - return fail(message || `Illegal value: ${member}`, stackCrawlMark || assertNever); + export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never { + const detail = "kind" in member && "pos" in member ? "SyntaxKind: " + showSyntaxKind(member as Node) : JSON.stringify(member); + return fail(`${message} ${detail}`, stackCrawlMark || assertNever); } export function getFunctionName(func: AnyFunction) { @@ -2124,4 +2130,8 @@ namespace ts { deleted(oldItems[oldIndex++]); } } + + export function fill(length: number, cb: (index: number) => T): T[] { + return new Array(length).fill(0).map((_, i) => cb(i)); + } } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 5939e581785..907940c4f6a 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2088,6 +2088,38 @@ "category": "Error", "code": 2577 }, + "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`.": { + "category": "Error", + "code": 2580 + }, + "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.": { + "category": "Error", + "code": 2581 + }, + "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.": { + "category": "Error", + "code": 2582 + }, + "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.": { + "category": "Error", + "code": 2583 + }, + "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.": { + "category": "Error", + "code": 2584 + }, + "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.": { + "category": "Error", + "code": 2585 + }, + "Enum type '{0}' circularly references itself.": { + "category": "Error", + "code": 2586 + }, + "JSDoc type '{0}' circularly references itself.": { + "category": "Error", + "code": 2587 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 @@ -2453,9 +2485,9 @@ "category": "Error", "code": 2732 }, - "Index '{0}' is out-of-bounds in tuple of length {1}.": { + "It is highly likely that you are missing a semicolon.": { "category": "Error", - "code": 2733 + "code": 2734 }, "Import declaration '{0}' is using private name '{1}'.": { @@ -2920,7 +2952,10 @@ "category": "Error", "code": 5072 }, - + "Build option '{0}' requires a value of type {1}.": { + "category": "Error", + "code": 5073 + }, "Generates a sourcemap for each corresponding '.d.ts' file.": { "category": "Message", @@ -3294,7 +3329,7 @@ "category": "Message", "code": 6104 }, - "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'.": { + "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'.": { "category": "Message", "code": 6105 }, @@ -3692,6 +3727,42 @@ "category": "Error", "code": 6205 }, + "'package.json' has a 'typesVersions' field with version-specific path mappings.": { + "category": "Message", + "code": 6206 + }, + "'package.json' does not have a 'typesVersions' entry that matches version '{0}'.": { + "category": "Message", + "code": 6207 + }, + "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'.": { + "category": "Message", + "code": 6208 + }, + "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range.": { + "category": "Message", + "code": 6209 + }, + "An argument for '{0}' was not provided.": { + "category": "Message", + "code": 6210 + }, + "An argument matching this binding pattern was not provided.": { + "category": "Message", + "code": 6211 + }, + "Did you mean to call this expression?": { + "category": "Message", + "code": 6212 + }, + "Did you mean to use 'new' with this expression?": { + "category": "Message", + "code": 6213 + }, + "Enable strict 'bind', 'call', and 'apply' methods on functions.": { + "category": "Message", + "code": 6214 + }, "Projects to reference": { "category": "Message", @@ -3814,10 +3885,6 @@ "category": "Error", "code": 6370 }, - "Skipping clean because not all projects could be located": { - "category": "Error", - "code": 6371 - }, "The expected type comes from property '{0}' which is declared here on type '{1}'": { "category": "Message", @@ -3827,6 +3894,10 @@ "category": "Message", "code": 6501 }, + "The expected type comes from the return type of this signature.": { + "category": "Message", + "code": 6502 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", @@ -4086,6 +4157,10 @@ "category": "Error", "code": 8030 }, + "You cannot rename a module via a global import.": { + "category": "Error", + "code": 8031 + }, "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.": { "category": "Error", "code": 9002 @@ -4584,7 +4659,7 @@ "category": "Message", "code": 95062 }, - + "Add missing enum member '{0}'": { "category": "Message", "code": 95063 @@ -4593,12 +4668,20 @@ "category": "Message", "code": 95064 }, - "Convert to async function":{ + "Convert to async function": { "category": "Message", - "code": 95065 + "code": 95065 }, "Convert all to async functions": { - "category": "Message", - "code": 95066 + "category": "Message", + "code": 95066 + }, + "Generate types for '{0}'": { + "category": "Message", + "code": 95067 + }, + "Generate types for all packages without types": { + "category": "Message", + "code": 95068 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 8cb1d4f34a9..8617c8fccde 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -41,20 +41,25 @@ namespace ts { export function getOutputPathsFor(sourceFile: SourceFile | Bundle, host: EmitHost, forceDtsPaths: boolean): EmitFileNames { const options = host.getCompilerOptions(); if (sourceFile.kind === SyntaxKind.Bundle) { - const jsFilePath = options.outFile || options.out!; - const sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - const declarationFilePath = (forceDtsPaths || getEmitDeclarations(options)) ? removeFileExtension(jsFilePath) + Extension.Dts : undefined; - const declarationMapPath = getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + const outPath = options.outFile || options.out!; + const jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + const sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + const declarationFilePath = (forceDtsPaths || getEmitDeclarations(options)) ? removeFileExtension(outPath) + Extension.Dts : undefined; + const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; const bundleInfoPath = options.references && jsFilePath ? (removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath }; } else { - const jsFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - const sourceMapFilePath = isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + const isJsonEmittedToSameLocation = isJsonSourceFile(sourceFile) && + comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === Comparison.EqualTo; + const jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + const sourceMapFilePath = !jsFilePath || isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - const isJs = isSourceFileJavaScript(sourceFile); + const isJs = isSourceFileJS(sourceFile); const declarationFilePath = ((forceDtsPaths || getEmitDeclarations(options)) && !isJs) ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - const declarationMapPath = getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath: undefined }; } } @@ -80,7 +85,7 @@ namespace ts { } if (options.jsx === JsxEmit.Preserve) { - if (isSourceFileJavaScript(sourceFile)) { + if (isSourceFileJS(sourceFile)) { if (fileExtensionIs(sourceFile.fileName, Extension.Jsx)) { return Extension.Jsx; } @@ -135,27 +140,33 @@ namespace ts { if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } - function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, jsFilePath: string, sourceMapFilePath: string | undefined, bundleInfoPath: string | undefined) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, jsFilePath: string | undefined, sourceMapFilePath: string | undefined, bundleInfoPath: string | undefined) { + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -187,12 +198,12 @@ namespace ts { } function emitDeclarationFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, declarationFilePath: string | undefined, declarationMapPath: string | undefined) { - if (!(declarationFilePath && !isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !isInJSFile(sourceFileOrBundle))) { return; } const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - const nonJsFiles = filter(sourceFiles, isSourceFileNotJavaScript); + const nonJsFiles = filter(sourceFiles, isSourceFileNotJS); const inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [createBundle(nonJsFiles, !isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -1015,7 +1026,7 @@ namespace ts { writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -1041,7 +1052,7 @@ namespace ts { // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node: LiteralLikeNode) { - const text = getLiteralTextOfNode(node); + const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -1532,7 +1543,7 @@ namespace ts { expression = skipPartiallyEmittedExpressions(expression); if (isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - const text = getLiteralTextOfNode(expression); + const text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !stringContains(text, tokenToString(SyntaxKind.DotToken)!); } @@ -2818,7 +2829,8 @@ namespace ts { const parameter = singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !some(parentNode.decorators) // parent may not have decorators && !some(parentNode.modifiers) // parent may not have modifiers && !some(parentNode.typeParameters) // parent may not have type parameters @@ -3305,20 +3317,20 @@ namespace ts { return getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node: LiteralLikeNode): string { + function getLiteralTextOfNode(node: LiteralLikeNode, neverAsciiEscape: boolean | undefined): string { if (node.kind === SyntaxKind.StringLiteral && (node).textSourceNode) { const textSourceNode = (node).textSourceNode!; if (isIdentifier(textSourceNode)) { - return getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? + return neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? `"${escapeString(getTextOfNode(textSourceNode))}"` : `"${escapeNonAsciiString(getTextOfNode(textSourceNode))}"`; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return getLiteralText(node, currentSourceFile); + return getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** @@ -3587,7 +3599,7 @@ namespace ts { } } - function makeFileLevelOptmiisticUniqueName(name: string) { + function makeFileLevelOptimisticUniqueName(name: string) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 984e6d59b2e..4b2855790a9 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -235,7 +235,7 @@ namespace ts { // Modifiers - export function createModifier(kind: T) { + export function createModifier(kind: T): Token { return createToken(kind); } diff --git a/src/compiler/inspectValue.ts b/src/compiler/inspectValue.ts new file mode 100644 index 00000000000..86b45b65031 --- /dev/null +++ b/src/compiler/inspectValue.ts @@ -0,0 +1,159 @@ +/* @internal */ +namespace ts { + export interface InspectValueOptions { + readonly fileNameToRequire: string; + } + + export const enum ValueKind { Const, Array, FunctionOrClass, Object } + export interface ValueInfoBase { + readonly name: string; + } + export type ValueInfo = ValueInfoSimple | ValueInfoArray | ValueInfoFunctionOrClass | ValueInfoObject; + export interface ValueInfoSimple extends ValueInfoBase { + readonly kind: ValueKind.Const; + readonly typeName: string; + readonly comment?: string | undefined; + } + export interface ValueInfoFunctionOrClass extends ValueInfoBase { + readonly kind: ValueKind.FunctionOrClass; + readonly source: string | number; // For a native function, this is the length. + readonly prototypeMembers: ReadonlyArray; + readonly namespaceMembers: ReadonlyArray; + } + export interface ValueInfoArray extends ValueInfoBase { + readonly kind: ValueKind.Array; + readonly inner: ValueInfo; + } + export interface ValueInfoObject extends ValueInfoBase { + readonly kind: ValueKind.Object; + readonly members: ReadonlyArray; + } + + export function inspectModule(fileNameToRequire: string): ValueInfo { + return inspectValue(removeFileExtension(getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + + export function inspectValue(name: string, value: unknown): ValueInfo { + return getValueInfo(name, value, getRecurser()); + } + + type Recurser = (obj: unknown, name: string, cbOk: () => T, cbFail: (isCircularReference: boolean, keyStack: ReadonlyArray) => T) => T; + function getRecurser(): Recurser { + const seen = new Set(); + const nameStack: string[] = []; + return (obj, name, cbOk, cbFail) => { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + + seen.add(obj); + nameStack.push(name); + const res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + + function getValueInfo(name: string, value: unknown, recurser: Recurser): ValueInfo { + return recurser(value, name, + (): ValueInfo => { + if (typeof value === "function") return getFunctionOrClassInfo(value as AnyFunction, name, recurser); + if (typeof value === "object") { + const builtin = getBuiltinType(name, value as object, recurser); + if (builtin !== undefined) return builtin; + const entries = getEntriesOfObject(value as object); + return { kind: ValueKind.Object, name, members: flatMap(entries, ({ key, value }) => getValueInfo(key, value, recurser)) }; + } + return { kind: ValueKind.Const, name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, + (isCircularReference, keyStack) => anyValue(name, ` ${isCircularReference ? "Circular reference" : "Too-deep object hierarchy"} from ${keyStack.join(".")}`)); + } + + function getFunctionOrClassInfo(fn: AnyFunction, name: string, recurser: Recurser): ValueInfoFunctionOrClass { + const prototypeMembers = getPrototypeMembers(fn, recurser); + const namespaceMembers = flatMap(getEntriesOfObject(fn), ({ key, value }) => getValueInfo(key, value, recurser)); + const toString = cast(Function.prototype.toString.call(fn), isString); + const source = stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: ValueKind.FunctionOrClass, name, source, namespaceMembers, prototypeMembers }; + } + + const builtins: () => ReadonlyMap = memoize(() => { + const map = createMap(); + for (const { key, value } of getEntriesOfObject(global)) { + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value as AnyConstructor); + } + } + return map; + }); + function getBuiltinType(name: string, value: object, recurser: Recurser): ValueInfo | undefined { + return isArray(value) + ? { name, kind: ValueKind.Array, inner: value.length && getValueInfo("element", first(value), recurser) || anyValue(name) } + : forEachEntry(builtins(), (builtin, builtinName): ValueInfo | undefined => + value instanceof builtin ? { kind: ValueKind.Const, name, typeName: builtinName } : undefined); + } + + function getPrototypeMembers(fn: AnyFunction, recurser: Recurser): ReadonlyArray { + const prototype = fn.prototype as unknown; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? emptyArray : mapDefined(getEntriesOfObject(prototype as object), ({ key, value }) => + key === "constructor" ? undefined : getValueInfo(key, value, recurser)); + } + + const ignoredProperties: ReadonlySet = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + const reservedFunctionProperties: ReadonlySet = new Set(Object.getOwnPropertyNames(noop)); + interface ObjectEntry { readonly key: string; readonly value: unknown; } + function getEntriesOfObject(obj: object): ReadonlyArray { + const seen = createMap(); + const entries: ObjectEntry[] = []; + let chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (const key of Object.getOwnPropertyNames(chain)) { + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + addToSeen(seen, key)) { + const value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key, value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort((e1, e2) => compareStringsCaseSensitive(e1.key, e2.key)); + } + + function getFunctionLength(fn: AnyFunction): number { + return tryCast(safeGetPropertyOfObject(fn, "length"), isNumber) || 0; + } + + function safeGetPropertyOfObject(obj: object, key: string): unknown { + const desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + + function isNullOrUndefined(value: unknown): value is null | undefined { + return value == null; // tslint:disable-line + } + + function anyValue(name: string, comment?: string): ValueInfo { + return { kind: ValueKind.Const, name, typeName: "any", comment }; + } + + export function isJsPrivate(name: string): boolean { + return name.startsWith("_"); + } + + function tryRequire(fileNameToRequire: string): unknown { + try { + return require(fileNameToRequire); + } + catch { + return undefined; + } + } +} diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 7fb308912c3..4906abc8f8c 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -24,6 +24,13 @@ namespace ts { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r: Resolved | undefined): PathAndExtension | undefined { + if (r) { + Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } + /** Result of trying to resolve a module. */ interface Resolved { path: string; @@ -67,7 +74,7 @@ namespace ts { if (!resolved) { return undefined; } - Debug.assert(extensionIsTypeScript(resolved.extension)); + Debug.assert(extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } @@ -82,12 +89,14 @@ namespace ts { host: ModuleResolutionHost; compilerOptions: CompilerOptions; traceEnabled: boolean; + failedLookupLocations: Push; } /** Just the fields that we use for module resolution. */ interface PackageJsonPathFields { typings?: string; types?: string; + typesVersions?: MapLike>; main?: string; } @@ -96,48 +105,111 @@ namespace ts { version?: string; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes: boolean, jsonContent: PackageJsonPathFields, baseDirectory: string, state: ModuleResolutionState): string | undefined { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); + type MatchingKeys = K extends (TRecord[K] extends TMatch ? K : never) ? K : never; - function tryReadFromField(fieldName: "typings" | "types" | "main"): string | undefined { - if (!hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - - const fileName = jsonContent[fieldName]; - if (!isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - - const path = normalizePath(combinePaths(baseDirectory, fileName)); + function readPackageJsonField>(jsonContent: PackageJson, fieldName: K, typeOfTag: "string", state: ModuleResolutionState): PackageJson[K] | undefined; + function readPackageJsonField>(jsonContent: PackageJson, fieldName: K, typeOfTag: "object", state: ModuleResolutionState): PackageJson[K] | undefined; + function readPackageJsonField(jsonContent: PackageJson, fieldName: K, typeOfTag: "string" | "object", state: ModuleResolutionState): PackageJson[K] | undefined { + if (!hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + const value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } - /* @internal */ - export function readJson(path: string, host: { readFile(fileName: string): string | undefined }): object { - try { - const jsonText = host.readFile(path); - if (!jsonText) return {}; - const result = parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; - } - return result.config; + function readPackageJsonPathField(jsonContent: PackageJson, fieldName: K, baseDirectory: string, state: ModuleResolutionState): PackageJson[K] | undefined { + const fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) return; + const path = normalizePath(combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; + return path; + } + + function readPackageJsonTypesFields(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + + function readPackageJsonMainField(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + + function readPackageJsonTypesVersionsField(jsonContent: PackageJson, state: ModuleResolutionState) { + const typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) return; + + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + + return typesVersions; + } + + interface VersionPaths { + version: string; + paths: MapLike; + } + + function readPackageJsonTypesVersionPaths(jsonContent: PackageJson, state: ModuleResolutionState): VersionPaths | undefined { + const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) return; + + if (state.traceEnabled) { + for (const key in typesVersions) { + if (hasProperty(typesVersions, key) && !VersionRange.tryParse(key)) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + + const result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor); + } + return; + } + + const { version: bestVersionKey, paths: bestVersionPaths } = result; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "object", typeof bestVersionPaths); + } + return; + } + + return result; + } + + let typeScriptVersion: Version | undefined; + + /* @internal */ + export function getPackageJsonTypesVersionsPaths(typesVersions: MapLike>) { + if (!typeScriptVersion) typeScriptVersion = new Version(version); + + for (const key in typesVersions) { + if (!hasProperty(typesVersions, key)) continue; + + const keyRange = VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; + } } } @@ -188,7 +260,8 @@ namespace ts { */ export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations { const traceEnabled = isTraceEnabled(options, host); - const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled }; + const failedLookupLocations: string[] = []; + const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled, failedLookupLocations }; const typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { @@ -210,8 +283,6 @@ namespace ts { } } - const failedLookupLocations: string[] = []; - let resolved = primaryLookup(); let primary = true; if (!resolved) { @@ -247,7 +318,7 @@ namespace ts { trace(host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } return resolvedTypeScriptOnly( - loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, + loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } @@ -266,7 +337,14 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - const result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + let result: SearchResult | undefined; + if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + const { path: candidate } = normalizePathAndParts(combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)); + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } const resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -304,14 +382,19 @@ namespace ts { if (host.directoryExists(root)) { for (const typeDirectivePath of host.getDirectories(root)) { const normalized = normalizePath(typeDirectivePath); - const packageJsonPath = pathToPackageJson(combinePaths(root, normalized)); + const packageJsonPath = combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword const isNotNeededPackage = host.fileExists(packageJsonPath) && (readJson(packageJsonPath, host) as PackageJson).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(getBaseFileName(normalized)); + const baseFileName = getBaseFileName(normalized); + + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== CharacterCodes.dot) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -527,7 +610,7 @@ namespace ts { * 'typings' entry or file 'index' with some supported extension * - Classic loader will only try to interpret '/a/b/c' as file. */ - type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined; + type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined; /** * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to @@ -590,18 +673,18 @@ namespace ts { * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ function tryLoadModuleUsingOptionalResolutionSettings(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, - failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { + state: ModuleResolutionState): Resolved | undefined { if (!isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } function tryLoadModuleUsingRootDirs(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, - failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { + state: ModuleResolutionState): Resolved | undefined { if (!state.compilerOptions.rootDirs) { return undefined; @@ -646,7 +729,7 @@ namespace ts { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - const resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -665,7 +748,7 @@ namespace ts { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate); } const baseDirectory = getDirectoryPath(candidate); - const resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -677,60 +760,28 @@ namespace ts { return undefined; } - function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined { + const { baseUrl, paths } = state.compilerOptions; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - - // string is for exact match - let matchedPattern: Pattern | string | undefined; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = matchPatternOrExact(getOwnKeys(state.compilerOptions.paths), moduleName); - } - - if (matchedPattern) { - const matchedStar = isString(matchedPattern) ? undefined : matchedText(matchedPattern, moduleName); - const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + const resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return forEach(state.compilerOptions.paths![matchedPatternText], subst => { - const path = matchedStar ? subst.replace("*", matchedStar) : subst; - const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl!, path)); - if (state.traceEnabled) { - trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - const extension = tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - const path = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path !== undefined) { - return noPackageId({ path, ext: extension }); - } - } - - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); - }); } - else { - const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName)); - - if (state.traceEnabled) { - trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); + const candidate = normalizePath(combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } - } - - export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { - return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + return loader(extensions, candidate, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); } /** @@ -739,20 +790,33 @@ namespace ts { * Throws an error if the module can't be resolved. */ /* @internal */ - export function resolveJavaScriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { - const { resolvedModule, failedLookupLocations } = - nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + export function resolveJSModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { + const { resolvedModule, failedLookupLocations } = tryResolveJSModuleWorker(moduleName, initialDir, host); if (!resolvedModule) { throw new Error(`Could not resolve JS module '${moduleName}' starting at '${initialDir}'. Looked in: ${failedLookupLocations.join(", ")}`); } return resolvedModule.resolvedFileName; } + /* @internal */ + export function tryResolveJSModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string | undefined { + const { resolvedModule } = tryResolveJSModuleWorker(moduleName, initialDir, host); + return resolvedModule && resolvedModule.resolvedFileName; + } + + function tryResolveJSModuleWorker(moduleName: string, initialDir: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { + return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, jsOnly: boolean): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; const result = jsOnly ? tryResolve(Extensions.JavaScript) : @@ -766,8 +830,8 @@ namespace ts { return { resolvedModule: undefined, failedLookupLocations }; function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> { - const loader: ResolutionKindSpecificLoader = (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); - const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); + const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved, isExternalLibraryImport: stringContains(resolved.path, nodeModulesPathPart) }); } @@ -776,7 +840,7 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - const resolved = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + const resolved = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved) return undefined; let resolvedValue = resolved.value; @@ -790,7 +854,7 @@ namespace ts { } else { const { path: candidate, parts } = normalizePathAndParts(combinePaths(containingDirectory, moduleName)); - const resolved = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + const resolved = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved && toSearchResult({ resolved, isExternalLibraryImport: contains(parts, "node_modules") }); } @@ -810,7 +874,7 @@ namespace ts { return real; } - function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson: boolean): Resolved | undefined { + function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson: boolean): Resolved | undefined { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } @@ -824,10 +888,11 @@ namespace ts { onlyRecordFailures = true; } } - const resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + const resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { const nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - const packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + const packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + const packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } @@ -840,7 +905,7 @@ namespace ts { onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ @@ -886,52 +951,46 @@ namespace ts { if (endsWith(path, ".d.ts")) { return path; } - if (endsWith(path, "/index")) { + if (path === "index" || endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean }): boolean { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - - function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { + function loadModuleFromFile(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { if (extensions === Extensions.Json) { const extensionLess = tryRemoveExtension(candidate, Extension.Json); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (hasJavaScriptFileExtension(candidate)) { + if (hasJSFileExtension(candidate)) { const extensionless = removeFileExtension(candidate); if (state.traceEnabled) { const extension = candidate.substring(extensionless.length); trace(state.host, Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate: string, extensions: Extensions, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { + function tryAddingExtensions(candidate: string, extensions: Extensions, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing const directory = getDirectoryPath(candidate); @@ -952,13 +1011,13 @@ namespace ts { } function tryExtension(ext: Extension): PathAndExtension | undefined { - const path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + const path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path, ext }; } } /** Return the file if it exists. */ - function tryFile(fileName: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined { + function tryFile(fileName: string, onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -972,48 +1031,40 @@ namespace ts { } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true) { - const { packageJsonContent, packageId } = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true) { + const packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + const packageId = packageInfo && packageInfo.packageId; + const packageJsonContent = packageInfo && packageInfo.packageJsonContent; + const versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, packageJsonContent: PackageJsonPathFields | undefined): PathAndExtension | undefined { - const fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + interface PackageJsonInfo { + packageJsonContent: PackageJsonPathFields | undefined; + packageId: PackageId | undefined; + versionPaths: VersionPaths | undefined; } - function getPackageJsonInfo( - nodeModuleDirectory: string, - subModuleName: string, - failedLookupLocations: Push, - onlyRecordFailures: boolean, - state: ModuleResolutionState, - ): { found: boolean, packageJsonContent: PackageJsonPathFields | undefined, packageId: PackageId | undefined } { + function getPackageJsonInfo(packageDirectory: string, subModuleName: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PackageJsonInfo | undefined { const { host, traceEnabled } = state; - const directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - const packageJsonPath = pathToPackageJson(nodeModuleDirectory); + const directoryExists = !onlyRecordFailures && directoryProbablyExists(packageDirectory, host); + const packageJsonPath = combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { const packageJsonContent = readJson(packageJsonPath, host) as PackageJson; if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - const path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + const path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - const jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - const potentialSubModule = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (forEach(supportedJavascriptExtensions, extension => + const jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + const potentialSubModule = jsPath.substring(packageDirectory.length + 1); + subModuleName = (forEach(supportedJSExtensions, extension => tryRemoveExtension(potentialSubModule, extension)) || potentialSubModule) + Extension.Dts; } else { @@ -1021,9 +1072,12 @@ namespace ts { } } } + if (!endsWith(subModuleName, Extension.Dts)) { subModuleName = addExtensionAndIndex(subModuleName); } + + const versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); const packageId: PackageId | undefined = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName, version: packageJsonContent.version } : undefined; @@ -1035,54 +1089,64 @@ namespace ts { trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent, packageId }; + + return { packageJsonContent, packageId, versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath); } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent: PackageJsonPathFields, extensions: Extensions, candidate: string, failedLookupLocations: Push, state: ModuleResolutionState): PathAndExtension | undefined { - let file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, jsonContent: PackageJsonPathFields | undefined, versionPaths: VersionPaths | undefined): PathAndExtension | undefined { + const packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + + const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => { + const fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + const resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(file), state.host); - const fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - const resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + const nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + + const onlyRecordFailuresForPackageFile = packageFile ? !directoryProbablyExists(getDirectoryPath(packageFile), state.host) : undefined; + const onlyRecordFailuresForIndex = onlyRecordFailures || !directoryProbablyExists(candidate, state.host); + const indexPath = combinePaths(candidate, "index"); + + if (versionPaths && (!packageFile || containsPath(candidate, packageFile))) { + const moduleName = getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, moduleName); + } + const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - const nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - const result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + const packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile!, state)); + if (packageFileResult) return packageFileResult; + + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ @@ -1105,34 +1169,8 @@ namespace ts { } } - function pathToPackageJson(directory: string): string { - return combinePaths(directory, "package.json"); - } - - function loadModuleFromNodeModulesFolder(extensions: Extensions, moduleName: string, nodeModulesFolder: string, nodeModulesFolderExists: boolean, failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { - const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - let packageJsonContent: PackageJsonPathFields | undefined; - let packageId: PackageId | undefined; - const packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - ({ packageJsonContent, packageId } = packageInfo); - } - else { - const { packageName, rest } = getPackageName(moduleName); - if (rest !== "") { // If "rest" is empty, we just did this search above. - const packageRootPath = combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - const pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } - /* @internal */ - export function getPackageName(moduleName: string): { packageName: string, rest: string } { + export function parsePackageName(moduleName: string): { packageName: string, rest: string } { let idx = moduleName.indexOf(directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(directorySeparator, idx + 1); @@ -1140,36 +1178,36 @@ namespace ts { return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - function loadModuleFromNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); - } - function loadModuleFromNodeModulesAtTypes(moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState): SearchResult { - // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + function loadModuleFromNearestNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesWorker(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName: string, directory: string, state: ModuleResolutionState): SearchResult { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); + } + + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, typesScopeOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return forEachAncestorDirectory(normalizeSlashes(directory), ancestorDirectory => { if (getBaseFileName(ancestorDirectory) !== "node_modules") { - const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly = false): Resolved | undefined { + function loadModuleFromImmediateNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, typesScopeOnly: boolean): Resolved | undefined { const nodeModulesFolder = combinePaths(directory, "node_modules"); const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - const packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + const packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } @@ -1182,7 +1220,84 @@ namespace ts { } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes, nodeModulesAtTypesExists, state); + } + } + + function loadModuleFromSpecificNodeModulesDirectory(extensions: Extensions, moduleName: string, nodeModulesDirectory: string, nodeModulesDirectoryExists: boolean, state: ModuleResolutionState): Resolved | undefined { + const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName)); + + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + let packageJsonContent: PackageJsonPathFields | undefined; + let packageId: PackageId | undefined; + let versionPaths: VersionPaths | undefined; + + const packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + ({ packageJsonContent, packageId, versionPaths } = packageInfo); + const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + + const fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + + const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => { + const pathAndExtension = + loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + + const { packageName, rest } = parsePackageName(moduleName); + if (rest !== "") { // If "rest" is empty, we just did this search above. + const packageDirectory = combinePaths(nodeModulesDirectory, packageName); + + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + const packageInfo = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo) ({ packageId, versionPaths } = packageInfo); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, rest); + } + const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host); + const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + + function tryLoadModuleUsingPaths(extensions: Extensions, moduleName: string, baseDirectory: string, paths: MapLike, loader: ResolutionKindSpecificLoader, onlyRecordFailures: boolean, state: ModuleResolutionState): SearchResult { + const matchedPattern = matchPatternOrExact(getOwnKeys(paths), moduleName); + if (matchedPattern) { + const matchedStar = isString(matchedPattern) ? undefined : matchedText(matchedPattern, moduleName); + const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + const resolved = forEach(paths[matchedPatternText], subst => { + const path = matchedStar ? subst.replace("*", matchedStar) : subst; + const candidate = normalizePath(combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + const extension = tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + const path = tryFile(candidate, onlyRecordFailures, state); + if (path !== undefined) { + return noPackageId({ path, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } @@ -1190,8 +1305,8 @@ namespace ts { const mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName: string, state: ModuleResolutionState): string { - const mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName: string, state: ModuleResolutionState): string { + const mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -1200,11 +1315,11 @@ namespace ts { /* @internal */ export function getTypesPackageName(packageName: string): string { - return `@types/${getMangledNameForScopedPackage(packageName)}`; + return `@types/${mangleScopedPackageName(packageName)}`; } /* @internal */ - export function getMangledNameForScopedPackage(packageName: string): string { + export function mangleScopedPackageName(packageName: string): string { if (startsWith(packageName, "@")) { const replaceSlash = packageName.replace(directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -1215,36 +1330,36 @@ namespace ts { } /* @internal */ - export function getPackageNameFromAtTypesDirectory(mangledName: string): string { + export function getPackageNameFromTypesPackageName(mangledName: string): string { const withoutAtTypePrefix = removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } /* @internal */ - export function getUnmangledNameForScopedPackage(typesPackageName: string): string { + export function unmangleScopedPackageName(typesPackageName: string): string { return stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) : typesPackageName; } - function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, traceEnabled: boolean, host: ModuleResolutionHost, failedLookupLocations: Push): SearchResult { + function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, state: ModuleResolutionState): SearchResult { const result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push(...result.failedLookupLocations); + state.failedLookupLocations.push(...result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; const failedLookupLocations: string[] = []; + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; const containingDirectory = getDirectoryPath(containingFile); const resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); @@ -1252,7 +1367,7 @@ namespace ts { return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions: Extensions): SearchResult { - const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -1261,24 +1376,24 @@ namespace ts { const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. const resolved = forEachAncestorDirectory(containingDirectory, directory => { - const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } const searchName = normalizePath(combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved) { return resolved; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -1293,9 +1408,9 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; const failedLookupLocations: string[] = []; - const resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; + const resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index eda480d032c..f28bc43e61a 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -30,7 +30,7 @@ namespace ts.moduleSpecifiers { function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpecifier: string): Preferences { return { relativePreference: isExternalModuleNameRelative(oldImportSpecifier) ? RelativePreference.Relative : RelativePreference.NonRelative, - ending: hasJavaScriptOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension + ending: hasJSOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension : getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs || endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal, }; } @@ -148,7 +148,7 @@ namespace ts.moduleSpecifiers { } function usesJsExtensionOnImports({ imports }: SourceFile): boolean { - return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJavaScriptOrJsonFileExtension(text) : undefined) || false; + return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJSOrJsonFileExtension(text) : undefined) || false; } function stringsEqual(a: string, b: string, getCanonicalFileName: GetCanonicalFileName): boolean { @@ -235,7 +235,8 @@ namespace ts.moduleSpecifiers { const suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && startsWith(relativeToBaseUrl, prefix) && - endsWith(relativeToBaseUrl, suffix)) { + endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === removeTrailingDirectorySeparator(prefix)) { const matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -259,11 +260,34 @@ namespace ts.moduleSpecifiers { } function tryGetModuleNameAsNodeModule(moduleFileName: string, { getCanonicalFileName, sourceDirectory }: Info, host: ModuleSpecifierResolutionHost, options: CompilerOptions): string | undefined { + if (!host.fileExists || !host.readFile) { + return undefined; + } const parts: NodeModulePathParts = getNodeModulePathParts(moduleFileName)!; if (!parts) { return undefined; } + const packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + const packageJsonPath = combinePaths(packageRootPath, "package.json"); + const packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)!) + : undefined; + const versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + const subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + const fromPaths = tryGetModuleNameFromPaths( + removeFileExtension(subModuleName), + removeExtensionAndIndexPostFix(subModuleName, Ending.Minimal, options), + versionPaths.paths + ); + if (fromPaths !== undefined) { + moduleFileName = combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } + // 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 @@ -274,23 +298,18 @@ namespace ts.moduleSpecifiers { // If the module was found in @types, get the actual Node package name const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); - const packageName = getPackageNameFromAtTypesDirectory(nodeModulesDirectoryName); + const packageName = getPackageNameFromTypesPackageName(nodeModulesDirectoryName); // For classic resolution, only allow importing from node_modules/@types, not other node_modules return getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path: string): string { // If the file is the main module, it can be imported by the package name - const packageRootPath = path.substring(0, parts.packageRootIndex); - const packageJsonPath = combinePaths(packageRootPath, "package.json"); - if (host.fileExists!(packageJsonPath)) { // TODO: GH#18217 - const packageJsonContent = JSON.parse(host.readFile!(packageJsonPath)!); - if (packageJsonContent) { - const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -309,11 +328,12 @@ namespace ts.moduleSpecifiers { } function tryGetAnyFileFromPath(host: ModuleSpecifierResolutionHost, path: string) { + if (!host.fileExists) return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory const extensions = getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: ScriptKind.JSON }]); for (const e of extensions) { const fullPath = path + e; - if (host.fileExists!(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -399,13 +419,13 @@ namespace ts.moduleSpecifiers { case Ending.Index: return noExtension; case Ending.JsExtension: - return noExtension + getJavaScriptExtensionForFile(fileName, options); + return noExtension + getJSExtensionForFile(fileName, options); default: return Debug.assertNever(ending); } } - function getJavaScriptExtensionForFile(fileName: string, options: CompilerOptions): Extension { + function getJSExtensionForFile(fileName: string, options: CompilerOptions): Extension { const ext = extensionFromPath(fileName); switch (ext) { case Extension.Ts: diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 1d65e31b490..c88aebe799f 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1482,7 +1482,15 @@ namespace ts { // which would be a candidate for improved error reporting. return token() === SyntaxKind.OpenBracketToken || isLiteralPropertyName(); case ParsingContext.ObjectLiteralMembers: - return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.AsteriskToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName(); + switch (token()) { + case SyntaxKind.OpenBracketToken: + case SyntaxKind.AsteriskToken: + case SyntaxKind.DotDotDotToken: + case SyntaxKind.DotToken: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case ParsingContext.RestProperties: return isLiteralPropertyName(); case ParsingContext.ObjectBindingElements: @@ -6308,7 +6316,7 @@ namespace ts { // Parses out a JSDoc type expression. export function parseJSDocTypeExpression(mayOmitBraces?: boolean): JSDocTypeExpression { - const result = createNode(SyntaxKind.JSDocTypeExpression, scanner.getTokenPos()); + const result = createNode(SyntaxKind.JSDocTypeExpression); const hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(SyntaxKind.OpenBraceToken); result.type = doInsideOfContext(NodeFlags.JSDoc, parseJSDocType); @@ -6441,13 +6449,6 @@ namespace ts { indent += asterisk.length; } break; - case SyntaxKind.Identifier: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = JSDocState.SavingComments; - break; case SyntaxKind.WhitespaceTrivia: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin const whitespace = scanner.getTokenText(); @@ -6462,7 +6463,9 @@ namespace ts { case SyntaxKind.EndOfFileToken: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = JSDocState.SavingComments; pushComment(scanner.getTokenText()); break; @@ -6542,7 +6545,7 @@ namespace ts { atToken.end = scanner.getTextPos(); nextJSDocToken(); - const tagName = parseJSDocIdentifierName(); + const tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); let tag: JSDocTag | undefined; @@ -6724,7 +6727,7 @@ namespace ts { } } - function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number | undefined): JSDocParameterTag | JSDocPropertyTag { + function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag { let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -6739,9 +6742,8 @@ namespace ts { const result = target === PropertyLikeParse.Property ? createNode(SyntaxKind.JSDocPropertyTag, atToken.pos) : createNode(SyntaxKind.JSDocParameterTag, atToken.pos); - let comment: string | undefined; - if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - const nestedTypeLiteral = target !== PropertyLikeParse.CallbackParameter && parseNestedTypeLiteral(typeExpression, name, target); + const comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + const nestedTypeLiteral = target !== PropertyLikeParse.CallbackParameter && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -6756,14 +6758,14 @@ namespace ts { return finishNode(result); } - function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression | undefined, name: EntityName, target: PropertyLikeParse) { + function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression | undefined, name: EntityName, target: PropertyLikeParse, indent: number) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { const typeLiteralExpression = createNode(SyntaxKind.JSDocTypeExpression, scanner.getTokenPos()); let child: JSDocPropertyLikeTag | JSDocTypeTag | false; let jsdocTypeLiteral: JSDocTypeLiteral; const start = scanner.getStartPos(); let children: JSDocPropertyLikeTag[] | undefined; - while (child = tryParse(() => parseChildParameterOrPropertyTag(target, name))) { + while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent, name))) { if (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) { children = append(children, child); } @@ -6879,7 +6881,7 @@ namespace ts { let jsdocTypeLiteral: JSDocTypeLiteral | undefined; let childTypeTag: JSDocTypeTag | undefined; const start = atToken.pos; - while (child = tryParse(() => parseChildPropertyTag())) { + while (child = tryParse(() => parseChildPropertyTag(indent))) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(SyntaxKind.JSDocTypeLiteral, start); } @@ -6945,7 +6947,7 @@ namespace ts { const start = scanner.getStartPos(); const jsdocSignature = createNode(SyntaxKind.JSDocSignature, start) as JSDocSignature; jsdocSignature.parameters = []; - while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter) as JSDocParameterTag)) { + while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter, indent) as JSDocParameterTag)) { jsdocSignature.parameters = append(jsdocSignature.parameters as MutableNodeArray, child); } const returnTag = tryParse(() => { @@ -6988,18 +6990,18 @@ namespace ts { return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(PropertyLikeParse.Property) as JSDocTypeTag | JSDocPropertyTag | false; + function parseChildPropertyTag(indent: number) { + return parseChildParameterOrPropertyTag(PropertyLikeParse.Property, indent) as JSDocTypeTag | JSDocPropertyTag | false; } - function parseChildParameterOrPropertyTag(target: PropertyLikeParse, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { + function parseChildParameterOrPropertyTag(target: PropertyLikeParse, indent: number, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { let canParseTag = true; let seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case SyntaxKind.AtToken: if (canParseTag) { - const child = tryParseChildTag(target); + const child = tryParseChildTag(target, indent); if (child && (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) && target !== PropertyLikeParse.CallbackParameter && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -7028,7 +7030,7 @@ namespace ts { } } - function tryParseChildTag(target: PropertyLikeParse): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { + function tryParseChildTag(target: PropertyLikeParse, indent: number): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { Debug.assert(token() === SyntaxKind.AtToken); const atToken = createNode(SyntaxKind.AtToken); atToken.end = scanner.getTextPos(); @@ -7055,9 +7057,7 @@ namespace ts { if (!(target & t)) { return false; } - const tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken: AtToken, tagName: Identifier): JSDocTemplateTag { @@ -7727,7 +7727,7 @@ namespace ts { /*@internal*/ export function processCommentPragmas(context: PragmaContext, sourceText: string): void { const triviaScanner = createScanner(context.languageVersion, /*skipTrivia*/ false, LanguageVariant.Standard, sourceText); - const pragmas: PragmaPsuedoMapEntry[] = []; + const pragmas: PragmaPseudoMapEntry[] = []; // Keep scanning all the leading trivia in the file until we get to something that // isn't trivia. Any single line comment will be analyzed to see if it is a @@ -7782,7 +7782,7 @@ namespace ts { const referencedFiles = context.referencedFiles; const typeReferenceDirectives = context.typeReferenceDirectives; const libReferenceDirectives = context.libReferenceDirectives; - forEach(toArray(entryOrList), (arg: PragmaPsuedoMap["reference"]) => { + forEach(toArray(entryOrList), (arg: PragmaPseudoMap["reference"]) => { // TODO: GH#18217 if (arg!.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; @@ -7805,7 +7805,7 @@ namespace ts { case "amd-dependency": { context.amdDependencies = map( toArray(entryOrList), - (x: PragmaPsuedoMap["amd-dependency"]) => ({ name: x!.arguments.name!, path: x!.arguments.path })); // TODO: GH#18217 + (x: PragmaPseudoMap["amd-dependency"]) => ({ name: x!.arguments.name!, path: x!.arguments.path })); // TODO: GH#18217 break; } case "amd-module": { @@ -7815,11 +7815,11 @@ namespace ts { // TODO: It's probably fine to issue this diagnostic on all instances of the pragma reportDiagnostic(entry!.range.pos, entry!.range.end - entry!.range.pos, Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); } - context.moduleName = (entry as PragmaPsuedoMap["amd-module"])!.arguments.name; + context.moduleName = (entry as PragmaPseudoMap["amd-module"])!.arguments.name; } } else { - context.moduleName = (entryOrList as PragmaPsuedoMap["amd-module"])!.arguments.name; + context.moduleName = (entryOrList as PragmaPseudoMap["amd-module"])!.arguments.name; } break; } @@ -7855,10 +7855,10 @@ namespace ts { const tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; const singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; - function extractPragmas(pragmas: PragmaPsuedoMapEntry[], range: CommentRange, text: string) { + function extractPragmas(pragmas: PragmaPseudoMapEntry[], range: CommentRange, text: string) { const tripleSlash = range.kind === SyntaxKind.SingleLineCommentTrivia && tripleSlashXMLCommentStartRegEx.exec(text); if (tripleSlash) { - const name = tripleSlash[1].toLowerCase() as keyof PragmaPsuedoMap; // Technically unsafe cast, but we do it so the below check to make it safe typechecks + const name = tripleSlash[1].toLowerCase() as keyof PragmaPseudoMap; // Technically unsafe cast, but we do it so the below check to make it safe typechecks const pragma = commentPragmas[name] as PragmaDefinition; if (!pragma || !(pragma.kind! & PragmaKindFlags.TripleSlashXML)) { return; @@ -7885,10 +7885,10 @@ namespace ts { } } } - pragmas.push({ name, args: { arguments: argument, range } } as PragmaPsuedoMapEntry); + pragmas.push({ name, args: { arguments: argument, range } } as PragmaPseudoMapEntry); } else { - pragmas.push({ name, args: { arguments: {}, range } } as PragmaPsuedoMapEntry); + pragmas.push({ name, args: { arguments: {}, range } } as PragmaPseudoMapEntry); } return; } @@ -7907,9 +7907,9 @@ namespace ts { } } - function addPragmaForMatch(pragmas: PragmaPsuedoMapEntry[], range: CommentRange, kind: PragmaKindFlags, match: RegExpExecArray) { + function addPragmaForMatch(pragmas: PragmaPseudoMapEntry[], range: CommentRange, kind: PragmaKindFlags, match: RegExpExecArray) { if (!match) return; - const name = match[1].toLowerCase() as keyof PragmaPsuedoMap; // Technically unsafe cast, but we do it so they below check to make it safe typechecks + const name = match[1].toLowerCase() as keyof PragmaPseudoMap; // Technically unsafe cast, but we do it so they below check to make it safe typechecks const pragma = commentPragmas[name] as PragmaDefinition; if (!pragma || !(pragma.kind! & kind)) { return; @@ -7917,7 +7917,7 @@ namespace ts { const args = match[2]; // Split on spaces and match up positionally with definition const argument = getNamedPragmaArguments(pragma, args); if (argument === "fail") return; // Missing required argument, fail to parse it - pragmas.push({ name, args: { arguments: argument, range } } as PragmaPsuedoMapEntry); + pragmas.push({ name, args: { arguments: argument, range } } as PragmaPseudoMapEntry); return; } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index c97f1a61d27..ccec076ce7e 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -207,7 +207,7 @@ namespace ts { ...program.getSemanticDiagnostics(sourceFile, cancellationToken) ]; - if (program.getCompilerOptions().declaration) { + if (getEmitDeclarations(program.getCompilerOptions())) { addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } @@ -250,7 +250,7 @@ namespace ts { Blue = "\u001b[94m", Cyan = "\u001b[96m" } - const gutterStyleSequence = "\u001b[30;47m"; + const gutterStyleSequence = "\u001b[7m"; const gutterSeparator = " "; const resetEscapeSequence = "\u001b[0m"; const ellipsis = "..."; @@ -442,6 +442,7 @@ namespace ts { fileExists: (fileName: string) => boolean, hasInvalidatedResolution: HasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: boolean, + projectReferences: ReadonlyArray | undefined ): boolean { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { @@ -453,6 +454,11 @@ namespace ts { return false; } + // If project references dont match + if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -477,9 +483,27 @@ namespace ts { return true; - function sourceFileNotUptoDate(sourceFile: SourceFile): boolean { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + function sourceFileNotUptoDate(sourceFile: SourceFile) { + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + + function sourceFileVersionUptoDate(sourceFile: SourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + + function projectReferenceUptoDate(oldRef: ProjectReference, newRef: ProjectReference, index: number) { + if (!projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + const oldResolvedRef = program!.getResolvedProjectReferences()![index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } @@ -490,23 +514,15 @@ namespace ts { } /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ - function shouldProgramCreateNewSourceFiles(program: Program | undefined, newOptions: CompilerOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - const oldOptions = program && program.getCompilerOptions(); - return oldOptions && ( - oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !equalOwnProperties(oldOptions.paths, newOptions.paths) - ); + function shouldProgramCreateNewSourceFiles(program: Program | undefined, newOptions: CompilerOptions): boolean { + if (!program) return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + const oldOptions = program.getCompilerOptions(); + return !!sourceFileAffectingCompilerOptions.some(option => + !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option))); } function createCreateProgramOptions(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): CreateProgramOptions { @@ -594,7 +610,7 @@ namespace ts { const programDiagnostics = createDiagnosticCollection(); const currentDirectory = host.getCurrentDirectory(); const supportedExtensions = getSupportedExtensions(options); - const supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? [...supportedExtensions, Extension.Json] : undefined; + const supportedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input const hasEmitBlockingDiagnostics = createMap(); @@ -647,7 +663,7 @@ namespace ts { // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files let resolvedProjectReferences: (ResolvedProjectReference | undefined)[] | undefined = projectReferences ? [] : undefined; - const projectReferenceRedirects: Map = createMap(); + let projectReferenceRedirects: ParsedCommandLine[] | undefined; const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); const structuralIsReused = tryReuseStructureFromOldProgram(); @@ -660,11 +676,12 @@ namespace ts { const parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences!.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - const dtsOutfile = changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + const out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + const dtsOutfile = changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -759,7 +776,9 @@ namespace ts { isEmittedFile, getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences + getProjectReferences, + getResolvedProjectReferences, + getProjectReferenceRedirect }; verifyCompilerOptions(); @@ -798,9 +817,9 @@ namespace ts { // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = getDirectoryPath(normalizeSlashes(options.configFilePath!)); // TODO: GH#18217 + commonSourceDirectory = getDirectoryPath(normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -1007,15 +1026,22 @@ namespace ts { } // Check if any referenced project tsconfig files are different - const oldRefs = oldProgram.getProjectReferences(); + + // If array of references is changed, we cant resue old program + const oldProjectReferences = oldProgram.getProjectReferences(); + if (!arrayIsEqualTo(oldProjectReferences!, projectReferences, projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = StructureIsReused.Not; + } + + // Check the json files for the project references + const oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = StructureIsReused.Not; - } + // Resolved project referenced should be array if projectReferences provided are array + Debug.assert(!!oldRefs); for (let i = 0; i < projectReferences.length; i++) { - const oldRef = oldRefs[i]; + const oldRef = oldRefs![i]; + const newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - const newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = StructureIsReused.Not; @@ -1023,16 +1049,15 @@ namespace ts { } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = StructureIsReused.Not; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = StructureIsReused.Not; - } + // Resolved project referenced should be undefined if projectReferences is undefined + Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program @@ -1054,7 +1079,7 @@ namespace ts { for (const oldSourceFile of oldSourceFiles) { let newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target!, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target!, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target!, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { @@ -1085,7 +1110,11 @@ namespace ts { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); const packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); @@ -1162,7 +1191,7 @@ namespace ts { modifiedFilePaths = modifiedSourceFiles.map(f => f.newFile.path); // try to verify results of module resolution for (const { oldFile: oldSourceFile, newFile: newSourceFile } of modifiedSourceFiles) { - const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { const moduleNames = getModuleNames(newSourceFile); const oldProgramState: OldProgramState = { program: oldProgram, oldSourceFile, modifiedFilePaths }; @@ -1219,7 +1248,14 @@ namespace ts { fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(ref => { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; @@ -1257,10 +1293,14 @@ namespace ts { }; } - function getProjectReferences() { + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } + function getPrependNodes(): InputFiles[] { if (!projectReferences) { return emptyArray; @@ -1271,12 +1311,13 @@ namespace ts { const ref = projectReferences[i]; const resolvedRefOpts = resolvedProjectReferences![i]!.commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + const out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) continue; + if (!out) continue; - const dtsFilename = changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - const js = host.readFile(resolvedRefOpts.options.outFile) || `/* Input file ${resolvedRefOpts.options.outFile} was missing */\r\n`; - const jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + const dtsFilename = changeExtension(out, ".d.ts"); + const js = host.readFile(out) || `/* Input file ${out} was missing */\r\n`; + const jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file const jsMap = host.readFile(jsMapPath); const dts = host.readFile(dtsFilename) || `/* Input file ${dtsFilename} was missing */\r\n`; const dtsMapPath = dtsFilename + ".map"; @@ -1351,7 +1392,7 @@ namespace ts { ...program.getSemanticDiagnostics(sourceFile, cancellationToken) ]; - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } @@ -1438,9 +1479,9 @@ namespace ts { function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): ReadonlyArray { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (isSourceFileJavaScript(sourceFile)) { + if (isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -1538,7 +1579,7 @@ namespace ts { return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] { + function getJSSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] { return runWithCancellationToken(() => { const diagnostics: DiagnosticWithLocation[] = []; let parent: Node = sourceFile; @@ -1801,7 +1842,7 @@ namespace ts { return; } - const isJavaScriptFile = isSourceFileJavaScript(file); + const isJavaScriptFile = isSourceFileJS(file); const isExternalModuleFile = isExternalModule(file); // file.imports may not be undefined if there exists dynamic import @@ -1924,7 +1965,7 @@ namespace ts { refFile?: SourceFile): SourceFile | undefined { if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { + if (!options.allowNonTsExtensions && !forEach(supportedExtensionsWithJsonIfResolveJsonModule, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { if (fail) fail(Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; } @@ -1983,11 +2024,14 @@ namespace ts { } } - function createRedirectSourceFile(redirectTarget: SourceFile, unredirected: SourceFile, fileName: string, path: Path): SourceFile { + function createRedirectSourceFile(redirectTarget: SourceFile, unredirected: SourceFile, fileName: string, path: Path, resolvedPath: Path, originalFileName: string): SourceFile { const redirect: SourceFile = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget, unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get(this: SourceFile) { return this.redirectInfo!.redirectTarget.id; }, @@ -2003,6 +2047,7 @@ namespace ts { // Get source file from normalized fileName function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, ignoreNoDefaultLib: boolean, refFile: SourceFile, refPos: number, refEnd: number, packageId: PackageId | undefined): SourceFile | undefined { + const originalFileName = fileName; if (filesByName.has(path)) { const file = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -2076,7 +2121,7 @@ namespace ts { if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - const dupFile = createRedirectSourceFile(fileFromPackageId, file!, fileName, path); // TODO: GH#18217 + const dupFile = createRedirectSourceFile(fileFromPackageId, file!, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -2099,6 +2144,7 @@ namespace ts { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { const pathLowerCase = path.toLowerCase(); @@ -2136,25 +2182,29 @@ namespace ts { } function getProjectReferenceRedirect(fileName: string): string | undefined { - const path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || fileExtensionIs(fileName, Extension.Dts) || !fileExtensionIsOneOf(fileName, supportedTSExtensions)) { + return undefined; + } + // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - const normalized = getNormalizedAbsolutePath(fileName, path); - let result: string | undefined; - projectReferenceRedirects.forEach((v, k) => { - if (result !== undefined) { + return forEach(projectReferenceRedirects, referencedProject => { + // not input file from the referenced project, ignore + if (!contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = changeExtension(fileName.replace(k, v), ".d.ts"); - } + + const out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + changeExtension(out, Extension.Dts) : + getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file: SourceFile, isDefaultLib: boolean) { forEach(file.referencedFiles, ref => { - const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + const referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -2166,7 +2216,7 @@ namespace ts { return; } - const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (let i = 0; i < typeDirectives.length; i++) { const ref = file.typeReferenceDirectives[i]; @@ -2262,7 +2312,7 @@ namespace ts { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. const moduleNames = getModuleNames(file); const oldProgramState: OldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths }; - const resolutions = resolveModuleNamesReusingOldState(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + const resolutions = resolveModuleNamesReusingOldState(moduleNames, getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); Debug.assert(resolutions.length === moduleNames.length); for (let i = 0; i < moduleNames.length; i++) { const resolution = resolutions[i]; @@ -2273,7 +2323,7 @@ namespace ts { } const isFromNodeModulesSearch = resolution.isExternalLibraryImport; - const isJsFile = !resolutionExtensionIsTypeScriptOrJson(resolution.extension); + const isJsFile = !resolutionExtensionIsTSOrJson(resolution.extension); const isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; const resolvedFileName = resolution.resolvedFileName; @@ -2295,7 +2345,7 @@ namespace ts { && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & NodeFlags.JSDoc)); + && (isInJSFile(file.imports[i]) || !(file.imports[i].flags & NodeFlags.JSDoc)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -2341,7 +2391,7 @@ namespace ts { function parseProjectReferenceConfigFile(ref: ProjectReference): { commandLine: ParsedCommandLine, sourceFile: SourceFile } | undefined { // The actual filename (i.e. add "/tsconfig.json" if necessary) - const refPath = resolveProjectReferencePath(host, ref); + const refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory()); const sourceFile = host.getSourceFile(refPath, ScriptTarget.JSON) as JsonSourceFile | undefined; @@ -2353,15 +2403,8 @@ namespace ts { return { commandLine, sourceFile }; } - function addProjectReferenceRedirects(referencedProject: ParsedCommandLine, target: Map) { - const rootDir = normalizePath(referencedProject.options.rootDir || getDirectoryPath(referencedProject.options.configFilePath!)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - - function getDeclarationOutputDirectory(proj: ParsedCommandLine) { - return proj.options.declarationDir || - proj.options.outDir || - getDirectoryPath(proj.options.configFilePath!); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject: ParsedCommandLine) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { @@ -2370,8 +2413,8 @@ namespace ts { } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { @@ -2418,9 +2461,10 @@ namespace ts { createDiagnosticForReference(i, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + const out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -2494,8 +2538,8 @@ namespace ts { } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); @@ -2503,7 +2547,7 @@ namespace ts { } if (options.declarationMap && !getEmitDeclarations(options)) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { @@ -2536,7 +2580,7 @@ namespace ts { } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) { createDiagnosticForOptionName(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -2571,8 +2615,8 @@ namespace ts { } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { @@ -2580,8 +2624,8 @@ namespace ts { } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { @@ -2794,7 +2838,7 @@ namespace ts { return containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (fileExtensionIsOneOf(filePath, supportedJavascriptExtensions) || fileExtensionIs(filePath, Extension.Dts)) { + if (fileExtensionIsOneOf(filePath, supportedJSExtensions) || fileExtensionIs(filePath, Extension.Dts)) { // Otherwise just check if sourceFile with the name exists const filePathWithoutExtension = removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + Extension.Ts) as Path) || @@ -2812,7 +2856,10 @@ namespace ts { export function parseConfigHostFromCompilerHost(host: CompilerHost): ParseConfigFileHost { return { fileExists: f => host.fileExists(f), - readDirectory: (root, extensions, includes, depth?) => host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : [], + readDirectory(root, extensions, excludes, includes, depth) { + Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory!(root, extensions, excludes, includes, depth); + }, readFile: f => host.readFile(f), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: () => host.getCurrentDirectory(), @@ -2820,20 +2867,25 @@ namespace ts { }; } - export interface ResolveProjectReferencePathHost { + // For backward compatibility + /** @deprecated */ export interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } + /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - export function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName { - if (!host.fileExists(ref.path)) { - return combinePaths(ref.path, "tsconfig.json") as ResolvedConfigFileName; - } - return ref.path as ResolvedConfigFileName; + export function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ export function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + export function resolveProjectReferencePath(hostOrRef: ResolveProjectReferencePathHost | ProjectReference, ref?: ProjectReference): ResolvedConfigFileName { + const passedInRef = ref ? ref : hostOrRef as ProjectReference; + return resolveConfigFileProjectName(passedInRef.path); } + function getEmitDeclarationOptionName(options: CompilerOptions) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 2d7bcb34c2d..84b5d8e0a85 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -226,7 +226,7 @@ namespace ts { // otherwise try to load typings from @types const globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results const { resolvedModule, failedLookupLocations } = loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache); @@ -398,7 +398,8 @@ namespace ts { function getDirectoryToWatchFailedLookupLocation(failedLookupLocation: string, failedLookupLocationPath: Path): DirectoryOfFailedLookupWatch { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, `FailedLookup: ${failedLookupLocation} failedLookupLocationPath: ${failedLookupLocationPath}`); // tslint:disable-line const subDirectoryInRoot = failedLookupLocationPath.indexOf(directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index b339220c38e..1a5c4336b63 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -60,81 +60,87 @@ namespace ts { tryScan(callback: () => T): T; } - const textToToken = createMapFromTemplate({ - "abstract": SyntaxKind.AbstractKeyword, - "any": SyntaxKind.AnyKeyword, - "as": SyntaxKind.AsKeyword, - "boolean": SyntaxKind.BooleanKeyword, - "break": SyntaxKind.BreakKeyword, - "case": SyntaxKind.CaseKeyword, - "catch": SyntaxKind.CatchKeyword, - "class": SyntaxKind.ClassKeyword, - "continue": SyntaxKind.ContinueKeyword, - "const": SyntaxKind.ConstKeyword, - "constructor": SyntaxKind.ConstructorKeyword, - "debugger": SyntaxKind.DebuggerKeyword, - "declare": SyntaxKind.DeclareKeyword, - "default": SyntaxKind.DefaultKeyword, - "delete": SyntaxKind.DeleteKeyword, - "do": SyntaxKind.DoKeyword, - "else": SyntaxKind.ElseKeyword, - "enum": SyntaxKind.EnumKeyword, - "export": SyntaxKind.ExportKeyword, - "extends": SyntaxKind.ExtendsKeyword, - "false": SyntaxKind.FalseKeyword, - "finally": SyntaxKind.FinallyKeyword, - "for": SyntaxKind.ForKeyword, - "from": SyntaxKind.FromKeyword, - "function": SyntaxKind.FunctionKeyword, - "get": SyntaxKind.GetKeyword, - "if": SyntaxKind.IfKeyword, - "implements": SyntaxKind.ImplementsKeyword, - "import": SyntaxKind.ImportKeyword, - "in": SyntaxKind.InKeyword, - "infer": SyntaxKind.InferKeyword, - "instanceof": SyntaxKind.InstanceOfKeyword, - "interface": SyntaxKind.InterfaceKeyword, - "is": SyntaxKind.IsKeyword, - "keyof": SyntaxKind.KeyOfKeyword, - "let": SyntaxKind.LetKeyword, - "module": SyntaxKind.ModuleKeyword, - "namespace": SyntaxKind.NamespaceKeyword, - "never": SyntaxKind.NeverKeyword, - "new": SyntaxKind.NewKeyword, - "null": SyntaxKind.NullKeyword, - "number": SyntaxKind.NumberKeyword, - "object": SyntaxKind.ObjectKeyword, - "package": SyntaxKind.PackageKeyword, - "private": SyntaxKind.PrivateKeyword, - "protected": SyntaxKind.ProtectedKeyword, - "public": SyntaxKind.PublicKeyword, - "readonly": SyntaxKind.ReadonlyKeyword, - "require": SyntaxKind.RequireKeyword, - "global": SyntaxKind.GlobalKeyword, - "return": SyntaxKind.ReturnKeyword, - "set": SyntaxKind.SetKeyword, - "static": SyntaxKind.StaticKeyword, - "string": SyntaxKind.StringKeyword, - "super": SyntaxKind.SuperKeyword, - "switch": SyntaxKind.SwitchKeyword, - "symbol": SyntaxKind.SymbolKeyword, - "this": SyntaxKind.ThisKeyword, - "throw": SyntaxKind.ThrowKeyword, - "true": SyntaxKind.TrueKeyword, - "try": SyntaxKind.TryKeyword, - "type": SyntaxKind.TypeKeyword, - "typeof": SyntaxKind.TypeOfKeyword, - "undefined": SyntaxKind.UndefinedKeyword, - "unique": SyntaxKind.UniqueKeyword, - "unknown": SyntaxKind.UnknownKeyword, - "var": SyntaxKind.VarKeyword, - "void": SyntaxKind.VoidKeyword, - "while": SyntaxKind.WhileKeyword, - "with": SyntaxKind.WithKeyword, - "yield": SyntaxKind.YieldKeyword, - "async": SyntaxKind.AsyncKeyword, - "await": SyntaxKind.AwaitKeyword, - "of": SyntaxKind.OfKeyword, + const textToKeywordObj: MapLike = { + abstract: SyntaxKind.AbstractKeyword, + any: SyntaxKind.AnyKeyword, + as: SyntaxKind.AsKeyword, + boolean: SyntaxKind.BooleanKeyword, + break: SyntaxKind.BreakKeyword, + case: SyntaxKind.CaseKeyword, + catch: SyntaxKind.CatchKeyword, + class: SyntaxKind.ClassKeyword, + continue: SyntaxKind.ContinueKeyword, + const: SyntaxKind.ConstKeyword, + ["" + "constructor"]: SyntaxKind.ConstructorKeyword, + debugger: SyntaxKind.DebuggerKeyword, + declare: SyntaxKind.DeclareKeyword, + default: SyntaxKind.DefaultKeyword, + delete: SyntaxKind.DeleteKeyword, + do: SyntaxKind.DoKeyword, + else: SyntaxKind.ElseKeyword, + enum: SyntaxKind.EnumKeyword, + export: SyntaxKind.ExportKeyword, + extends: SyntaxKind.ExtendsKeyword, + false: SyntaxKind.FalseKeyword, + finally: SyntaxKind.FinallyKeyword, + for: SyntaxKind.ForKeyword, + from: SyntaxKind.FromKeyword, + function: SyntaxKind.FunctionKeyword, + get: SyntaxKind.GetKeyword, + if: SyntaxKind.IfKeyword, + implements: SyntaxKind.ImplementsKeyword, + import: SyntaxKind.ImportKeyword, + in: SyntaxKind.InKeyword, + infer: SyntaxKind.InferKeyword, + instanceof: SyntaxKind.InstanceOfKeyword, + interface: SyntaxKind.InterfaceKeyword, + is: SyntaxKind.IsKeyword, + keyof: SyntaxKind.KeyOfKeyword, + let: SyntaxKind.LetKeyword, + module: SyntaxKind.ModuleKeyword, + namespace: SyntaxKind.NamespaceKeyword, + never: SyntaxKind.NeverKeyword, + new: SyntaxKind.NewKeyword, + null: SyntaxKind.NullKeyword, + number: SyntaxKind.NumberKeyword, + object: SyntaxKind.ObjectKeyword, + package: SyntaxKind.PackageKeyword, + private: SyntaxKind.PrivateKeyword, + protected: SyntaxKind.ProtectedKeyword, + public: SyntaxKind.PublicKeyword, + readonly: SyntaxKind.ReadonlyKeyword, + require: SyntaxKind.RequireKeyword, + global: SyntaxKind.GlobalKeyword, + return: SyntaxKind.ReturnKeyword, + set: SyntaxKind.SetKeyword, + static: SyntaxKind.StaticKeyword, + string: SyntaxKind.StringKeyword, + super: SyntaxKind.SuperKeyword, + switch: SyntaxKind.SwitchKeyword, + symbol: SyntaxKind.SymbolKeyword, + this: SyntaxKind.ThisKeyword, + throw: SyntaxKind.ThrowKeyword, + true: SyntaxKind.TrueKeyword, + try: SyntaxKind.TryKeyword, + type: SyntaxKind.TypeKeyword, + typeof: SyntaxKind.TypeOfKeyword, + undefined: SyntaxKind.UndefinedKeyword, + unique: SyntaxKind.UniqueKeyword, + unknown: SyntaxKind.UnknownKeyword, + var: SyntaxKind.VarKeyword, + void: SyntaxKind.VoidKeyword, + while: SyntaxKind.WhileKeyword, + with: SyntaxKind.WithKeyword, + yield: SyntaxKind.YieldKeyword, + async: SyntaxKind.AsyncKeyword, + await: SyntaxKind.AwaitKeyword, + of: SyntaxKind.OfKeyword, + }; + + const textToKeyword = createMapFromTemplate(textToKeywordObj); + + const textToToken = createMapFromTemplate({ + ...textToKeywordObj, "{": SyntaxKind.OpenBraceToken, "}": SyntaxKind.CloseBraceToken, "(": SyntaxKind.OpenParenToken, @@ -1288,15 +1294,15 @@ namespace ts { return result; } - function getIdentifierToken(): SyntaxKind { + function getIdentifierToken(): SyntaxKind.Identifier | KeywordSyntaxKind { // Reserved words are between 2 and 11 characters long and start with a lowercase letter const len = tokenValue.length; if (len >= 2 && len <= 11) { const ch = tokenValue.charCodeAt(0); if (ch >= CharacterCodes.a && ch <= CharacterCodes.z) { - token = textToToken.get(tokenValue)!; - if (token !== undefined) { - return token; + const keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -2016,7 +2022,7 @@ namespace ts { pos++; } tokenValue = text.substring(tokenPos, pos); - return token = SyntaxKind.Identifier; + return token = getIdentifierToken(); } else { return token = SyntaxKind.Unknown; diff --git a/src/compiler/semver.ts b/src/compiler/semver.ts new file mode 100644 index 00000000000..33623f45542 --- /dev/null +++ b/src/compiler/semver.ts @@ -0,0 +1,391 @@ +/* @internal */ +namespace ts { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + const versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + const prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + const buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + const numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + + /** + * Describes a precise semantic version number, https://semver.org + */ + export class Version { + static readonly zero = new Version(0, 0, 0); + + readonly major: number; + readonly minor: number; + readonly patch: number; + readonly prerelease: ReadonlyArray; + readonly build: ReadonlyArray; + + constructor(text: string); + constructor(major: number, minor?: number, patch?: number, prerelease?: string, build?: string); + constructor(major: number | string, minor = 0, patch = 0, prerelease = "", build = "") { + if (typeof major === "string") { + const result = Debug.assertDefined(tryParseComponents(major), "Invalid version"); + ({ major, minor, patch, prerelease, build } = result); + } + + Debug.assert(major >= 0, "Invalid argument: major"); + Debug.assert(minor >= 0, "Invalid argument: minor"); + Debug.assert(patch >= 0, "Invalid argument: patch"); + Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : emptyArray; + this.build = build ? build.split(".") : emptyArray; + } + + static tryParse(text: string) { + const result = tryParseComponents(text); + if (!result) return undefined; + + const { major, minor, patch, prerelease, build } = result; + return new Version(major, minor, patch, prerelease, build); + } + + compareTo(other: Version | undefined) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) return Comparison.EqualTo; + if (other === undefined) return Comparison.GreaterThan; + return compareValues(this.major, other.major) + || compareValues(this.minor, other.minor) + || compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + } + + increment(field: "major" | "minor" | "patch") { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return Debug.assertNever(field); + } + } + + toString() { + let result = `${this.major}.${this.minor}.${this.patch}`; + if (some(this.prerelease)) result += `-${this.prerelease.join(".")}`; + if (some(this.build)) result += `+${this.build.join(".")}`; + return result; + } + } + + function tryParseComponents(text: string) { + const match = versionRegExp.exec(text); + if (!match) return undefined; + + const [, major, minor = "0", patch = "0", prerelease = "", build = ""] = match; + if (prerelease && !prereleaseRegExp.test(prerelease)) return undefined; + if (build && !buildRegExp.test(build)) return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease, + build + }; + } + + function comparePrerelaseIdentifiers(left: ReadonlyArray, right: ReadonlyArray) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) return Comparison.EqualTo; + if (left.length === 0) return right.length === 0 ? Comparison.EqualTo : Comparison.GreaterThan; + if (right.length === 0) return Comparison.LessThan; + + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftIdentifier = left[i]; + const rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) continue; + + const leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + const rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) return leftIsNumeric ? Comparison.LessThan : Comparison.GreaterThan; + + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + const result = compareValues(+leftIdentifier, +rightIdentifier); + if (result) return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + const result = compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) return result; + } + } + + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return compareValues(left.length, right.length); + } + + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + export class VersionRange { + private _alternatives: ReadonlyArray>; + + constructor(spec: string) { + this._alternatives = spec ? Debug.assertDefined(parseRange(spec), "Invalid range spec.") : emptyArray; + } + + static tryParse(text: string) { + const sets = parseRange(text); + if (sets) { + const range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + } + + test(version: Version | string) { + if (typeof version === "string") version = new Version(version); + return testDisjunction(version, this._alternatives); + } + + toString() { + return formatDisjunction(this._alternatives); + } + } + + interface Comparator { + readonly operator: "<" | "<=" | ">" | ">=" | "="; + readonly operand: Version; + } + + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + const logicalOrRegExp = /\s*\|\|\s*/g; + const whitespaceRegExp = /\s+/g; + + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + const partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + const hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + const rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + + function parseRange(text: string) { + const alternatives: Comparator[][] = []; + for (const range of text.trim().split(logicalOrRegExp)) { + if (!range) continue; + const comparators: Comparator[] = []; + const match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) return undefined; + } + else { + for (const simple of range.split(whitespaceRegExp)) { + const match = rangeRegExp.exec(simple); + if (!match || !parseComparator(match[1], match[2], comparators)) return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + + function parsePartial(text: string) { + const match = partialRegExp.exec(text); + if (!match) return undefined; + + const [, major, minor = "*", patch = "*", prerelease, build] = match; + const version = new Version( + isWildcard(major) ? 0 : parseInt(major, 10), + isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), + isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), + prerelease, + build); + + return { version, major, minor, patch }; + } + + function parseHyphen(left: string, right: string, comparators: Comparator[]) { + const leftResult = parsePartial(left); + if (!leftResult) return false; + + const rightResult = parsePartial(right); + if (!rightResult) return false; + + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + + if (!isWildcard(rightResult.major)) { + comparators.push( + isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + + return true; + } + + function parseComparator(operator: string, text: string, comparators: Comparator[]) { + const result = parsePartial(text); + if (!result) return false; + + const { version, major, minor, patch } = result; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment( + isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment( + version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push( + isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + + return true; + } + + function isWildcard(part: string) { + return part === "*" || part === "x" || part === "X"; + } + + function createComparator(operator: Comparator["operator"], operand: Version) { + return { operator, operand }; + } + + function testDisjunction(version: Version, alternatives: ReadonlyArray>) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) return true; + for (const alternative of alternatives) { + if (testAlternative(version, alternative)) return true; + } + return false; + } + + function testAlternative(version: Version, comparators: ReadonlyArray) { + for (const comparator of comparators) { + if (!testComparator(version, comparator.operator, comparator.operand)) return false; + } + return true; + } + + function testComparator(version: Version, operator: Comparator["operator"], operand: Version) { + const cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return Debug.assertNever(operator); + } + } + + function formatDisjunction(alternatives: ReadonlyArray>) { + return map(alternatives, formatAlternative).join(" || ") || "*"; + } + + function formatAlternative(comparators: ReadonlyArray) { + return map(comparators, formatComparator).join(" "); + } + + function formatComparator(comparator: Comparator) { + return `${comparator.operator}${comparator.operand}`; + } +} \ No newline at end of file diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index eaa910a0b5c..8ee1e4571b3 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -36,23 +36,6 @@ namespace ts { Low = 250 } - function getPriorityValues(highPriorityValue: number): [number, number, number] { - const mediumPriorityValue = highPriorityValue * 2; - const lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - - function pollingInterval(watchPriority: PollingInterval): number { - return pollingIntervalsForPriority[watchPriority]; - } - - const pollingIntervalsForPriority = getPriorityValues(250); - - /* @internal */ - export function watchFileUsingPriorityPollingInterval(host: System, fileName: string, callback: FileWatcherCallback, watchPriority: PollingInterval): FileWatcher { - return host.watchFile!(fileName, callback, pollingInterval(watchPriority)); - } - /* @internal */ export type HostWatchFile = (fileName: string, callback: FileWatcherCallback, pollingInterval: PollingInterval | undefined) => FileWatcher; /* @internal */ @@ -317,18 +300,22 @@ namespace ts { const newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - const eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } + /*@internal*/ + export function getFileWatcherEventKind(oldTime: number, newTime: number) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + /*@internal*/ export interface RecursiveDirectoryWatcherHost { watchDirectory: HostWatchDirectory; @@ -792,11 +779,10 @@ namespace ts { dirName, (_eventName: string, relativeFileName) => { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - const fileName = !isString(relativeFileName) - ? undefined! // TODO: GH#18217 - : getNormalizedAbsolutePath(relativeFileName, dirName); + if (!isString(relativeFileName)) { return; } + const fileName = getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - const callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + const callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (const fileCallback of callbacks) { fileCallback(fileName, FileWatcherEventKind.Changed); @@ -843,7 +829,7 @@ namespace ts { } } - type FsWatchCallback = (eventName: "rename" | "change", relativeFileName: string) => void; + type FsWatchCallback = (eventName: "rename" | "change", relativeFileName: string | undefined) => void; function createFileWatcherCallback(callback: FsWatchCallback): FileWatcherCallback { return (_fileName, eventKind) => callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index f31058743a2..00e787c421b 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -1,11 +1,11 @@ /*@internal*/ namespace ts { export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, file: SourceFile | undefined): DiagnosticWithLocation[] | undefined { - if (file && isSourceFileJavaScript(file)) { + if (file && isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } const compilerOptions = host.getCompilerOptions(); - const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } @@ -157,7 +157,7 @@ namespace ts { function transformRoot(node: SourceFile): SourceFile; function transformRoot(node: SourceFile | Bundle): SourceFile | Bundle; function transformRoot(node: SourceFile | Bundle) { - if (node.kind === SyntaxKind.SourceFile && (node.isDeclarationFile || isSourceFileJavaScript(node))) { + if (node.kind === SyntaxKind.SourceFile && (node.isDeclarationFile || isSourceFileJS(node))) { return node; } @@ -168,7 +168,7 @@ namespace ts { let hasNoDefaultLib = false; const bundle = createBundle(map(node.sourceFiles, sourceFile => { - if (sourceFile.isDeclarationFile || isSourceFileJavaScript(sourceFile)) return undefined!; // Omit declaration files from bundle results, too // TODO: GH#18217 + if (sourceFile.isDeclarationFile || isSourceFileJS(sourceFile)) return undefined!; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; @@ -275,7 +275,7 @@ namespace ts { else { if (isBundledEmit && contains((node as Bundle).sourceFiles, file)) return; // Omit references to files which are being merged const paths = getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { @@ -289,6 +289,13 @@ namespace ts { if (startsWith(fileName, "./") && hasExtension(fileName)) { fileName = fileName.substring(2); } + + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } + references.push({ pos: -1, end: -1, fileName }); } }; @@ -296,7 +303,7 @@ namespace ts { } function collectReferences(sourceFile: SourceFile, ret: Map) { - if (noResolve || isSourceFileJavaScript(sourceFile)) return ret; + if (noResolve || isSourceFileJS(sourceFile)) return ret; forEach(sourceFile.referencedFiles, f => { const elem = tryResolveScriptReference(host, sourceFile, f); if (elem) { @@ -982,7 +989,7 @@ namespace ts { ensureType(input, input.type), /*body*/ undefined )); - if (clean && resolver.isJSContainerFunctionDeclaration(input)) { + if (clean && resolver.isExpandoFunctionDeclaration(input)) { const declarations = mapDefined(resolver.getPropertiesOfContainerFunction(input), p => { if (!isPropertyAccessExpression(p.valueDeclaration)) { return undefined; diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 0865861414e..94d6994f8d2 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -434,7 +434,7 @@ namespace ts { // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = (node as ExpressionWithTypeArguments).parent.token === SyntaxKind.ImplementsKeyword ? + diagnosticMessage = isHeritageClause(node.parent) && node.parent.token === SyntaxKind.ImplementsKeyword ? Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -446,7 +446,7 @@ namespace ts { return { diagnosticMessage, errorNode: node, - typeName: getNameOfDeclaration((node as ExpressionWithTypeArguments).parent.parent) + typeName: getNameOfDeclaration(node.parent.parent as Declaration) }; } @@ -466,4 +466,4 @@ namespace ts { }; } } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/destructuring.ts b/src/compiler/transformers/destructuring.ts index 14d1659dc76..cde5ee290a3 100644 --- a/src/compiler/transformers/destructuring.ts +++ b/src/compiler/transformers/destructuring.ts @@ -307,8 +307,8 @@ namespace ts { if (!getRestIndicatorOfBindingOrAssignmentElement(element)) { const propertyName = getPropertyNameOfBindingOrAssignmentElement(element)!; if (flattenContext.level >= FlattenLevel.ObjectRest - && !(element.transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest)) - && !(getTargetOfBindingOrAssignmentElement(element)!.transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest)) + && !(element.transformFlags & (TransformFlags.ContainsRestOrSpread | TransformFlags.ContainsObjectRestOrSpread)) + && !(getTargetOfBindingOrAssignmentElement(element)!.transformFlags & (TransformFlags.ContainsRestOrSpread | TransformFlags.ContainsObjectRestOrSpread)) && !isComputedPropertyName(propertyName)) { bindingElements = append(bindingElements, element); } @@ -384,7 +384,7 @@ namespace ts { if (flattenContext.level >= FlattenLevel.ObjectRest) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & TransformFlags.ContainsObjectRest) { + if (element.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { const temp = createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index dcb0d9ac208..66f635a31e9 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -46,10 +46,16 @@ namespace ts { * so nobody can observe this new value. */ interface LoopOutParameter { + flags: LoopOutParameterFlags; originalName: Identifier; outParamName: Identifier; } + const enum LoopOutParameterFlags { + Body = 1 << 0, // Modified in the body of the iteration statement + Initializer = 1 << 1, // Set in the initializer of a ForStatement + } + const enum CopyDirection { ToOriginal, ToOutParameter @@ -129,10 +135,14 @@ namespace ts { */ hoistedLocalVariables?: Identifier[]; + conditionVariable?: Identifier; + + loopParameters: ParameterDeclaration[]; + /** * List of loop out parameters - detailed descripion can be found in the comment to LoopOutParameter */ - loopOutParameters?: LoopOutParameter[]; + loopOutParameters: LoopOutParameter[]; } const enum SuperCaptureResult { @@ -347,7 +357,7 @@ namespace ts { return (node.transformFlags & TransformFlags.ContainsES2015) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & HierarchyFacts.ConstructorWithCapturedSuper && (isStatement(node) || (node.kind === SyntaxKind.Block))) - || (isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (getEmitFlags(node) & EmitFlags.TypeScriptClassWrapper) !== 0; } @@ -646,8 +656,8 @@ namespace ts { } } let returnExpression: Expression = createLiteral(labelMarker); - if (convertedLoopState.loopOutParameters!.length) { - const outParams = convertedLoopState.loopOutParameters!; + if (convertedLoopState.loopOutParameters.length) { + const outParams = convertedLoopState.loopOutParameters; let expr: Expression | undefined; for (let i = 0; i < outParams.length; i++) { const copyExpr = copyOutParameter(outParams[i], CopyDirection.ToOutParameter); @@ -2610,7 +2620,40 @@ namespace ts { return visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node: IterationStatement): boolean { + interface ForStatementWithConvertibleInitializer extends ForStatement { + initializer: VariableDeclarationList; + } + + interface ForStatementWithConvertibleCondition extends ForStatement { + condition: Expression; + } + + interface ForStatementWithConvertibleIncrementor extends ForStatement { + incrementor: Expression; + } + + function shouldConvertPartOfIterationStatement(node: Node) { + return (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ContainsCapturedBlockScopeBinding) !== 0; + } + + function shouldConvertInitializerOfForStatement(node: IterationStatement): node is ForStatementWithConvertibleInitializer { + return isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + + function shouldConvertConditionOfForStatement(node: IterationStatement): node is ForStatementWithConvertibleCondition { + return isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + + function shouldConvertIncrementorOfForStatement(node: IterationStatement): node is ForStatementWithConvertibleIncrementor { + return isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + + function shouldConvertIterationStatement(node: IterationStatement) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + + function shouldConvertBodyOfIterationStatement(node: IterationStatement): boolean { return (resolver.getNodeCheckFlags(node) & NodeCheckFlags.LoopWithCapturedBlockScopedBinding) !== 0; } @@ -2639,7 +2682,7 @@ namespace ts { } function convertIterationStatementBodyIfNecessary(node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, convert?: LoopConverter): VisitResult { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { let saveAllowedNonLabeledJumps: Jump | undefined; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -2658,7 +2701,102 @@ namespace ts { return result; } - const functionName = createUniqueName("_loop"); + const currentState = createConvertedLoopState(node); + const statements: Statement[] = []; + + const outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + + const initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + const bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + + convertedLoopState = outerConvertedLoopState; + + if (initializerFunction) statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) statements.push(bodyFunction.functionDeclaration); + + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + + let loop: Statement; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + const clone = convertIterationStatementCore(node, initializerFunction, createBlock(bodyFunction.part, /*multiLine*/ true)); + aggregateTransformFlags(clone); + loop = restoreEnclosingLabel(clone, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + const clone = convertIterationStatementCore(node, initializerFunction, visitNode(node.statement, visitor, isStatement, liftToBlock)); + aggregateTransformFlags(clone); + loop = restoreEnclosingLabel(clone, outermostLabeledStatement, convertedLoopState && resetLabel); + } + + statements.push(loop); + return statements; + } + + function convertIterationStatementCore(node: IterationStatement, initializerFunction: IterationStatementPartFunction | undefined, convertedLoopBody: Statement) { + switch (node.kind) { + case SyntaxKind.ForStatement: return convertForStatement(node as ForStatement, initializerFunction, convertedLoopBody); + case SyntaxKind.ForInStatement: return convertForInStatement(node as ForInStatement, convertedLoopBody); + case SyntaxKind.ForOfStatement: return convertForOfStatement(node as ForOfStatement, convertedLoopBody); + case SyntaxKind.DoStatement: return convertDoStatement(node as DoStatement, convertedLoopBody); + case SyntaxKind.WhileStatement: return convertWhileStatement(node as WhileStatement, convertedLoopBody); + default: return Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + + function convertForStatement(node: ForStatement, initializerFunction: IterationStatementPartFunction | undefined, convertedLoopBody: Statement) { + const shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + const shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return updateFor( + node, + visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, isForInitializer), + visitNode(shouldConvertCondition ? undefined : node.condition, visitor, isExpression), + visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, isExpression), + convertedLoopBody + ); + } + + function convertForOfStatement(node: ForOfStatement, convertedLoopBody: Statement) { + return updateForOf( + node, + /*awaitModifier*/ undefined, + visitNode(node.initializer, visitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + convertedLoopBody); + } + + function convertForInStatement(node: ForInStatement, convertedLoopBody: Statement) { + return updateForIn( + node, + visitNode(node.initializer, visitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + convertedLoopBody); + } + + function convertDoStatement(node: DoStatement, convertedLoopBody: Statement) { + return updateDo( + node, + convertedLoopBody, + visitNode(node.expression, visitor, isExpression)); + } + + function convertWhileStatement(node: WhileStatement, convertedLoopBody: Statement) { + return updateWhile( + node, + visitNode(node.expression, visitor, isExpression), + convertedLoopBody); + } + + function createConvertedLoopState(node: IterationStatement) { let loopInitializer: VariableDeclarationList | undefined; switch (node.kind) { case SyntaxKind.ForStatement: @@ -2670,74 +2808,311 @@ namespace ts { } break; } + // variables that will be passed to the loop as parameters const loopParameters: ParameterDeclaration[] = []; // variables declared in the loop initializer that will be changed inside the loop const loopOutParameters: LoopOutParameter[] = []; if (loopInitializer && (getCombinedNodeFlags(loopInitializer) & NodeFlags.BlockScoped)) { + const hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (const decl of loopInitializer.declarations) { - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - const outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters }; - if (outerConvertedLoopState) { + const currentState: ConvertedLoopState = { loopParameters, loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; + } + } + return currentState; + } + + function addExtraDeclarationsForConvertedLoop(statements: Statement[], state: ConvertedLoopState, outerState: ConvertedLoopState | undefined) { + let extraVariableDeclarations: VariableDeclaration[] | undefined; + // propagate state from the inner loop to the outer loop if necessary + if (state.argumentsName) { + // if alias for arguments is set + if (outerState) { + // pass it to outer converted loop + outerState.argumentsName = state.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push( + createVariableDeclaration( + state.argumentsName, + /*type*/ undefined, + createIdentifier("arguments") + ) + ); } } + if (state.thisName) { + // if alias for this is set + if (outerState) { + // pass it to outer converted loop + outerState.thisName = state.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push( + createVariableDeclaration( + state.thisName, + /*type*/ undefined, + createIdentifier("this") + ) + ); + } + } + + if (state.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerState) { + // pass them to outer converted loop + outerState.hoistedLocalVariables = state.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (const identifier of state.hoistedLocalVariables) { + extraVariableDeclarations.push(createVariableDeclaration(identifier)); + } + } + } + + // add extra variables to hold out parameters if necessary + if (state.loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (const outParam of state.loopOutParameters) { + extraVariableDeclarations.push(createVariableDeclaration(outParam.outParamName)); + } + } + + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(createVariableDeclaration(state.conditionVariable, /*type*/ undefined, createFalse())); + } + + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(createVariableStatement( + /*modifiers*/ undefined, + createVariableDeclarationList(extraVariableDeclarations) + )); + } + } + + interface IterationStatementPartFunction { + functionName: Identifier; + functionDeclaration: Statement; + containsYield: boolean; + part: T; + } + + function createOutVariable(p: LoopOutParameter) { + return createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node: ForStatementWithConvertibleInitializer, currentState: ConvertedLoopState): IterationStatementPartFunction { + const functionName = createUniqueName("_loop_init"); + + const containsYield = (node.initializer.transformFlags & TransformFlags.ContainsYield) !== 0; + let emitFlags = EmitFlags.None; + if (currentState.containsLexicalThis) emitFlags |= EmitFlags.CapturesThis; + if (containsYield && hierarchyFacts & HierarchyFacts.AsyncFunctionBody) emitFlags |= EmitFlags.AsyncFunctionBody; + + const statements: Statement[] = []; + statements.push(createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, LoopOutParameterFlags.Initializer, CopyDirection.ToOutParameter, statements); + + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + + const functionDeclaration = createVariableStatement( + /*modifiers*/ undefined, + setEmitFlags( + createVariableDeclarationList([ + createVariableDeclaration( + functionName, + /*type*/ undefined, + setEmitFlags( + createFunctionExpression( + /*modifiers*/ undefined, + containsYield ? createToken(SyntaxKind.AsteriskToken) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, + visitNode( + createBlock(statements, /*multiLine*/ true), + visitor, + isBlock + ) + ), + emitFlags + ) + ) + ]), + EmitFlags.NoHoisting + ) + ); + + const part = createVariableDeclarationList(map(currentState.loopOutParameters, createOutVariable)); + return { functionName, containsYield, functionDeclaration, part }; + } + + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node: IterationStatement, currentState: ConvertedLoopState, outerState: ConvertedLoopState | undefined): IterationStatementPartFunction { + const functionName = createUniqueName("_loop"); startLexicalEnvironment(); - let loopBody = visitNode(node.statement, visitor, isStatement, liftToBlock); + const statement = visitNode(node.statement, visitor, isStatement, liftToBlock); const lexicalEnvironment = endLexicalEnvironment(); - const currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; + const statements: Statement[] = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. - if (loopOutParameters.length || lexicalEnvironment) { - const statements = isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, CopyDirection.ToOutParameter, statements); + currentState.conditionVariable = createUniqueName("inc"); + statements.push(createIf( + currentState.conditionVariable, + createStatement(visitNode(node.incrementor, visitor, isExpression)), + createStatement(createAssignment(currentState.conditionVariable, createTrue())) + )); + + if (shouldConvertConditionOfForStatement(node)) { + statements.push(createIf( + createPrefix(SyntaxKind.ExclamationToken, visitNode(node.condition, visitor, isExpression)), + visitNode(createBreak(), visitor, isStatement) + )); } - addStatementsAfterPrologue(statements, lexicalEnvironment); - loopBody = createBlock(statements, /*multiline*/ true); } - if (isBlock(loopBody)) { - loopBody.multiLine = true; + if (isBlock(statement)) { + addRange(statements, statement.statements); } else { - loopBody = createBlock([loopBody], /*multiline*/ true); + statements.push(statement); } + copyOutParameters(currentState.loopOutParameters, LoopOutParameterFlags.Body, CopyDirection.ToOutParameter, statements); + addStatementsAfterPrologue(statements, lexicalEnvironment); + + const loopBody = createBlock(statements, /*multiLine*/ true); + if (isBlock(statement)) setOriginalNode(loopBody, statement); + const containsYield = (node.statement.transformFlags & TransformFlags.ContainsYield) !== 0; - const isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & HierarchyFacts.AsyncFunctionBody) !== 0; - let loopBodyFlags: EmitFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= EmitFlags.CapturesThis; - } + let emitFlags: EmitFlags = 0; + if (currentState.containsLexicalThis) emitFlags |= EmitFlags.CapturesThis; + if (containsYield && (hierarchyFacts & HierarchyFacts.AsyncFunctionBody) !== 0) emitFlags |= EmitFlags.AsyncFunctionBody; - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= EmitFlags.AsyncFunctionBody; - } + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } - const convertedLoopVariable = + const functionDeclaration = createVariableStatement( /*modifiers*/ undefined, setEmitFlags( @@ -2752,11 +3127,11 @@ namespace ts { containsYield ? createToken(SyntaxKind.AsteriskToken) : undefined, /*name*/ undefined, /*typeParameters*/ undefined, - loopParameters, + currentState.loopParameters, /*type*/ undefined, - loopBody + loopBody ), - loopBodyFlags + emitFlags ) ) ] @@ -2765,106 +3140,8 @@ namespace ts { ) ); - const statements: Statement[] = [convertedLoopVariable]; - - let extraVariableDeclarations: VariableDeclaration[] | undefined; - // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { - // if alias for arguments is set - if (outerConvertedLoopState) { - // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; - } - else { - // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push( - createVariableDeclaration( - currentState.argumentsName, - /*type*/ undefined, - createIdentifier("arguments") - ) - ); - } - } - - if (currentState.thisName) { - // if alias for this is set - if (outerConvertedLoopState) { - // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; - } - else { - // this is top level converted loop so we need to create an alias for 'this' here - // NOTE: - // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. - // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push( - createVariableDeclaration( - currentState.thisName, - /*type*/ undefined, - createIdentifier("this") - ) - ); - } - } - - if (currentState.hoistedLocalVariables) { - // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { - // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; - } - else { - if (!extraVariableDeclarations) { - extraVariableDeclarations = []; - } - // hoist collected variable declarations - for (const identifier of currentState.hoistedLocalVariables) { - extraVariableDeclarations.push(createVariableDeclaration(identifier)); - } - } - } - - // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { - if (!extraVariableDeclarations) { - extraVariableDeclarations = []; - } - for (const outParam of loopOutParameters) { - extraVariableDeclarations.push(createVariableDeclaration(outParam.outParamName)); - } - } - - // create variable statement to hold all introduced variable declarations - if (extraVariableDeclarations) { - statements.push(createVariableStatement( - /*modifiers*/ undefined, - createVariableDeclarationList(extraVariableDeclarations) - )); - } - - const convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - - let loop: Statement; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); - } - else { - let clone = getMutableClone(node); - // clean statement part - clone.statement = undefined!; - // visit childnodes to transform initializer/condition/incrementor parts - clone = visitEachChild(clone, visitor, context); - // set loop statement - clone.statement = createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone.transformFlags = 0; - aggregateTransformFlags(clone); - loop = restoreEnclosingLabel(clone, outermostLabeledStatement, convertedLoopState && resetLabel); - } - - statements.push(loop); - return statements; + const part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName, containsYield, functionDeclaration, part }; } function copyOutParameter(outParam: LoopOutParameter, copyDirection: CopyDirection): BinaryExpression { @@ -2873,14 +3150,26 @@ namespace ts { return createBinary(target, SyntaxKind.EqualsToken, source); } - function copyOutParameters(outParams: LoopOutParameter[], copyDirection: CopyDirection, statements: Statement[]): void { + function copyOutParameters(outParams: LoopOutParameter[], partFlags: LoopOutParameterFlags, copyDirection: CopyDirection, statements: Statement[]): void { for (const outParam of outParams) { - statements.push(createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName: Identifier, parameters: ParameterDeclaration[], state: ConvertedLoopState, isAsyncBlockContainingAwait: boolean): Statement[] { - const outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName: Identifier, containsYield: boolean): Statement { + const call = createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + const callResult = containsYield + ? createYield( + createToken(SyntaxKind.AsteriskToken), + setEmitFlags(call, EmitFlags.Iterator) + ) + : call; + return createStatement(callResult); + } + + function generateCallToConvertedLoop(loopFunctionExpressionName: Identifier, state: ConvertedLoopState, outerState: ConvertedLoopState | undefined, containsYield: boolean): Statement[] { const statements: Statement[] = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop @@ -2891,8 +3180,8 @@ namespace ts { !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - const call = createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, map(parameters, p => p.name)); - const callResult = isAsyncBlockContainingAwait + const call = createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, map(state.loopParameters, p => p.name)); + const callResult = containsYield ? createYield( createToken(SyntaxKind.AsteriskToken), setEmitFlags(call, EmitFlags.Iterator) @@ -2900,7 +3189,7 @@ namespace ts { : call; if (isSimpleLoop) { statements.push(createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters!, CopyDirection.ToOriginal, statements); + copyOutParameters(state.loopOutParameters, LoopOutParameterFlags.Body, CopyDirection.ToOriginal, statements); } else { const loopResultName = createUniqueName("state"); @@ -2911,12 +3200,12 @@ namespace ts { ) ); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters!, CopyDirection.ToOriginal, statements); + copyOutParameters(state.loopOutParameters, LoopOutParameterFlags.Body, CopyDirection.ToOriginal, statements); if (state.nonLocalJumps! & Jump.Return) { let returnStatement: ReturnStatement; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps! |= Jump.Return; + if (outerState) { + outerState.nonLocalJumps! |= Jump.Return; returnStatement = createReturn(loopResultName); } else { @@ -2949,8 +3238,8 @@ namespace ts { if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { const caseClauses: CaseClause[] = []; - processLabeledJumps(state.labeledNonLocalBreaks!, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues!, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks!, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues!, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push( createSwitch( loopResultName, @@ -2998,20 +3287,28 @@ namespace ts { }); } - function processLoopVariableDeclaration(decl: VariableDeclaration | BindingElement, loopParameters: ParameterDeclaration[], loopOutParameters: LoopOutParameter[]) { + function processLoopVariableDeclaration(container: IterationStatement, decl: VariableDeclaration | BindingElement, loopParameters: ParameterDeclaration[], loopOutParameters: LoopOutParameter[], hasCapturedBindingsInForInitializer: boolean) { const name = decl.name; if (isBindingPattern(name)) { for (const element of name.elements) { if (!isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & NodeCheckFlags.NeedsLoopOutParameter) { + const checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & NodeCheckFlags.NeedsLoopOutParameter || hasCapturedBindingsInForInitializer) { const outParamName = createUniqueName("out_" + idText(name)); - loopOutParameters.push({ originalName: name, outParamName }); + let flags: LoopOutParameterFlags = 0; + if (checkFlags & NodeCheckFlags.NeedsLoopOutParameter) { + flags |= LoopOutParameterFlags.Body; + } + if (isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= LoopOutParameterFlags.Initializer; + } + loopOutParameters.push({ flags, originalName: name, outParamName }); } } } @@ -3432,7 +3729,7 @@ namespace ts { function visitCallExpressionWithPotentialCapturedThisAssignment(node: CallExpression, assignToCapturedThis: boolean): CallExpression | BinaryExpression { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & TransformFlags.ContainsSpread || + if (node.transformFlags & TransformFlags.ContainsRestOrSpread || node.expression.kind === SyntaxKind.SuperKeyword || isSuperProperty(skipOuterExpressions(node.expression))) { @@ -3442,7 +3739,7 @@ namespace ts { } let resultingCall: CallExpression | BinaryExpression; - if (node.transformFlags & TransformFlags.ContainsSpread) { + if (node.transformFlags & TransformFlags.ContainsRestOrSpread) { // [source] // f(...a, b) // x.m(...a, b) @@ -3505,7 +3802,7 @@ namespace ts { * @param node A NewExpression node. */ function visitNewExpression(node: NewExpression): LeftHandSideExpression { - if (node.transformFlags & TransformFlags.ContainsSpread) { + if (node.transformFlags & TransformFlags.ContainsRestOrSpread) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -4079,7 +4376,7 @@ namespace ts { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index f58a24fb0a9..b509c6dd003 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -32,6 +32,15 @@ namespace ts { let enclosingFunctionParameterNames: UnderscoreEscapedMap; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + let capturedSuperProperties: UnderscoreEscapedMap; + /** Whether the async function contains an element access on super (`super[x]`). */ + let hasSuperElementAccess: boolean; + /** A set of node IDs for generated super accessors (variable statements). */ + const substitutedSuperAccessors: boolean[] = []; + // Save the previous transformation hooks. const previousOnEmitNode = context.onEmitNode; const previousOnSubstituteNode = context.onSubstituteNode; @@ -56,7 +65,6 @@ namespace ts { if ((node.transformFlags & TransformFlags.ContainsES2017) === 0) { return node; } - switch (node.kind) { case SyntaxKind.AsyncKeyword: // ES2017 async modifier should be elided for targets < ES2017 @@ -77,6 +85,18 @@ namespace ts { case SyntaxKind.ArrowFunction: return visitArrowFunction(node); + case SyntaxKind.PropertyAccessExpression: + if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return visitEachChild(node, visitor, context); + + case SyntaxKind.ElementAccessExpression: + if (capturedSuperProperties && (node).expression.kind === SyntaxKind.SuperKeyword) { + hasSuperElementAccess = true; + } + return visitEachChild(node, visitor, context); + default: return visitEachChild(node, visitor, context); } @@ -398,6 +418,11 @@ namespace ts { recordDeclarationName(parameter, enclosingFunctionParameterNames); } + const savedCapturedSuperProperties = capturedSuperProperties; + const savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + let result: ConciseBody; if (!isArrowFunction) { const statements: Statement[] = []; @@ -415,18 +440,26 @@ namespace ts { addStatementsAfterPrologue(statements, endLexicalEnvironment()); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 && resolver.getNodeCheckFlags(node) & (NodeCheckFlags.AsyncMethodWithSuperBinding | NodeCheckFlags.AsyncMethodWithSuper); + + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + const variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[getNodeId(variableStatement)] = true; + addStatementsAfterPrologue(statements, [variableStatement]); + } + const block = createBlock(statements, /*multiLine*/ true); setTextRange(block, node.body); - // Minor optimization, emit `_super` helper to capture `super` access in an arrow. - // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= ScriptTarget.ES2015) { + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) { - enableSubstitutionForAsyncMethodsWithSuper(); addEmitHelper(block, advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) { - enableSubstitutionForAsyncMethodsWithSuper(); addEmitHelper(block, asyncSuperHelper); } } @@ -452,6 +485,8 @@ namespace ts { } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } @@ -493,6 +528,8 @@ namespace ts { context.enableEmitNotification(SyntaxKind.GetAccessor); context.enableEmitNotification(SyntaxKind.SetAccessor); context.enableEmitNotification(SyntaxKind.Constructor); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(SyntaxKind.VariableStatement); } } @@ -516,6 +553,14 @@ namespace ts { return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) { + const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } @@ -548,8 +593,10 @@ namespace ts { function substitutePropertyAccessExpression(node: PropertyAccessExpression) { if (node.expression.kind === SyntaxKind.SuperKeyword) { - return createSuperAccessInAsyncMethod( - createLiteral(idText(node.name)), + return setTextRange( + createPropertyAccess( + createFileLevelUniqueName("_super"), + node.name), node ); } @@ -558,7 +605,7 @@ namespace ts { function substituteElementAccessExpression(node: ElementAccessExpression) { if (node.expression.kind === SyntaxKind.SuperKeyword) { - return createSuperAccessInAsyncMethod( + return createSuperElementAccessInAsyncMethod( node.argumentExpression, node ); @@ -593,12 +640,12 @@ namespace ts { || kind === SyntaxKind.SetAccessor; } - function createSuperAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression { + function createSuperElementAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression { if (enclosingSuperContainerFlags & NodeCheckFlags.AsyncMethodWithSuperBinding) { return setTextRange( createPropertyAccess( createCall( - createFileLevelUniqueName("_super"), + createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression] ), @@ -610,7 +657,7 @@ namespace ts { else { return setTextRange( createCall( - createFileLevelUniqueName("_super"), + createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression] ), @@ -620,6 +667,89 @@ namespace ts { } } + /** Creates a variable named `_super` with accessor properties for the given property names. */ + export function createSuperAccessVariableStatement(resolver: EmitResolver, node: FunctionLikeDeclaration, names: UnderscoreEscapedMap) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + const hasBinding = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) !== 0; + const accessors: PropertyAssignment[] = []; + names.forEach((_, key) => { + const name = unescapeLeadingUnderscores(key); + const getterAndSetter: PropertyAssignment[] = []; + getterAndSetter.push(createPropertyAssignment( + "get", + createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, + createPropertyAccess( + createSuper(), + name + ) + ) + )); + if (hasBinding) { + getterAndSetter.push( + createPropertyAssignment( + "set", + createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, + "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined + ) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, + createAssignment( + createPropertyAccess( + createSuper(), + name), + createIdentifier("v") + ) + ) + ) + ); + } + accessors.push( + createPropertyAssignment( + name, + createObjectLiteral(getterAndSetter), + ) + ); + }); + return createVariableStatement( + /* modifiers */ undefined, + createVariableDeclarationList( + [ + createVariableDeclaration( + createFileLevelUniqueName("_super"), + /* type */ undefined, + createCall( + createPropertyAccess( + createIdentifier("Object"), + "create" + ), + /* typeArguments */ undefined, + [ + createNull(), + createObjectLiteral(accessors, /* multiline */ true) + ] + ) + ) + ], + NodeFlags.Const)); + } + const awaiterHelper: EmitHelper = { name: "typescript:awaiter", scoped: false, @@ -667,14 +797,14 @@ namespace ts { name: "typescript:async-super", scoped: true, text: helperString` - const ${"_super"} = name => super[name];` + const ${"_superIndex"} = name => super[name];` }; export const advancedAsyncSuperHelper: EmitHelper = { name: "typescript:advanced-async-super", scoped: true, text: helperString` - const ${"_super"} = (function (geti, seti) { + const ${"_superIndex"} = (function (geti, seti) { const cache = Object.create(null); return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); })(name => super[name], (name, value) => super[name] = value);` diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index b121eb315db..cd62cca2c9d 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -26,6 +26,13 @@ namespace ts { let enclosingFunctionFlags: FunctionFlags; let enclosingSuperContainerFlags: NodeCheckFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + let capturedSuperProperties: UnderscoreEscapedMap; + /** Whether the async function contains an element access on super (`super[x]`). */ + let hasSuperElementAccess: boolean; + /** A set of node IDs for generated super accessors. */ + const substitutedSuperAccessors: boolean[] = []; + return chainBundle(transformSourceFile); function transformSourceFile(node: SourceFile) { @@ -57,7 +64,6 @@ namespace ts { if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) { return node; } - switch (node.kind) { case SyntaxKind.AwaitExpression: return visitAwaitExpression(node as AwaitExpression); @@ -101,6 +107,16 @@ namespace ts { return visitParenthesizedExpression(node as ParenthesizedExpression, noDestructuringValue); case SyntaxKind.CatchClause: return visitCatchClause(node as CatchClause); + case SyntaxKind.PropertyAccessExpression: + if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return visitEachChild(node, visitor, context); + case SyntaxKind.ElementAccessExpression: + if (capturedSuperProperties && (node).expression.kind === SyntaxKind.SuperKeyword) { + hasSuperElementAccess = true; + } + return visitEachChild(node, visitor, context); default: return visitEachChild(node, visitor, context); } @@ -210,7 +226,7 @@ namespace ts { } function visitObjectLiteralExpression(node: ObjectLiteralExpression): Expression { - if (node.transformFlags & TransformFlags.ContainsObjectSpread) { + if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -250,7 +266,7 @@ namespace ts { * @param node A BinaryExpression node. */ function visitBinaryExpression(node: BinaryExpression, noDestructuringValue: boolean): Expression { - if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.ContainsObjectRest) { + if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { return flattenDestructuringAssignment( node, visitor, @@ -276,7 +292,7 @@ namespace ts { */ function visitVariableDeclaration(node: VariableDeclaration): VisitResult { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (isBindingPattern(node.name) && node.name.transformFlags & TransformFlags.ContainsObjectRest) { + if (isBindingPattern(node.name) && node.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { return flattenDestructuringBinding( node, visitor, @@ -307,7 +323,7 @@ namespace ts { * @param node A ForOfStatement. */ function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined): VisitResult { - if (node.initializer.transformFlags & TransformFlags.ContainsObjectRest) { + if (node.initializer.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -499,7 +515,7 @@ namespace ts { } function visitParameter(node: ParameterDeclaration): ParameterDeclaration { - if (node.transformFlags & TransformFlags.ContainsObjectRest) { + if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return updateParameter( @@ -655,41 +671,57 @@ namespace ts { const statementOffset = addPrologue(statements, node.body!.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push( - createReturn( - createAsyncGeneratorHelper( - context, - createFunctionExpression( - /*modifiers*/ undefined, - createToken(SyntaxKind.AsteriskToken), - node.name && getGeneratedNameForNode(node.name), - /*typeParameters*/ undefined, - /*parameters*/ [], - /*type*/ undefined, - updateBlock( - node.body!, - visitLexicalEnvironment(node.body!.statements, visitor, context, statementOffset) - ) + const savedCapturedSuperProperties = capturedSuperProperties; + const savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + + const returnStatement = createReturn( + createAsyncGeneratorHelper( + context, + createFunctionExpression( + /*modifiers*/ undefined, + createToken(SyntaxKind.AsteriskToken), + node.name && getGeneratedNameForNode(node.name), + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + updateBlock( + node.body!, + visitLexicalEnvironment(node.body!.statements, visitor, context, statementOffset) ) ) ) ); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 && resolver.getNodeCheckFlags(node) & (NodeCheckFlags.AsyncMethodWithSuperBinding | NodeCheckFlags.AsyncMethodWithSuper); + + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + const variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[getNodeId(variableStatement)] = true; + addStatementsAfterPrologue(statements, [variableStatement]); + } + + statements.push(returnStatement); + addStatementsAfterPrologue(statements, endLexicalEnvironment()); const block = updateBlock(node.body!, statements); - // Minor optimization, emit `_super` helper to capture `super` access in an arrow. - // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= ScriptTarget.ES2015) { + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) { - enableSubstitutionForAsyncMethodsWithSuper(); addEmitHelper(block, advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) { - enableSubstitutionForAsyncMethodsWithSuper(); addEmitHelper(block, asyncSuperHelper); } } + + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return block; } @@ -716,7 +748,7 @@ namespace ts { function appendObjectRestAssignmentsIfNeeded(statements: Statement[] | undefined, node: FunctionLikeDeclaration): Statement[] | undefined { for (const parameter of node.parameters) { - if (parameter.transformFlags & TransformFlags.ContainsObjectRest) { + if (parameter.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { const temp = getGeneratedNameForNode(parameter); const declarations = flattenDestructuringBinding( parameter, @@ -758,6 +790,8 @@ namespace ts { context.enableEmitNotification(SyntaxKind.GetAccessor); context.enableEmitNotification(SyntaxKind.SetAccessor); context.enableEmitNotification(SyntaxKind.Constructor); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(SyntaxKind.VariableStatement); } } @@ -781,6 +815,14 @@ namespace ts { return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) { + const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0 as NodeCheckFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } @@ -813,8 +855,10 @@ namespace ts { function substitutePropertyAccessExpression(node: PropertyAccessExpression) { if (node.expression.kind === SyntaxKind.SuperKeyword) { - return createSuperAccessInAsyncMethod( - createLiteral(idText(node.name)), + return setTextRange( + createPropertyAccess( + createFileLevelUniqueName("_super"), + node.name), node ); } @@ -823,7 +867,7 @@ namespace ts { function substituteElementAccessExpression(node: ElementAccessExpression) { if (node.expression.kind === SyntaxKind.SuperKeyword) { - return createSuperAccessInAsyncMethod( + return createSuperElementAccessInAsyncMethod( node.argumentExpression, node ); @@ -858,12 +902,12 @@ namespace ts { || kind === SyntaxKind.SetAccessor; } - function createSuperAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression { + function createSuperElementAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression { if (enclosingSuperContainerFlags & NodeCheckFlags.AsyncMethodWithSuperBinding) { return setTextRange( createPropertyAccess( createCall( - createIdentifier("_super"), + createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression] ), @@ -875,7 +919,7 @@ namespace ts { else { return setTextRange( createCall( - createIdentifier("_super"), + createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression] ), diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 7af0b7c5ad7..a5ab1e8475f 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -973,9 +973,11 @@ namespace ts { // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - const hasInstancePropertyWithInitializer = forEach(node.members, isInstanceInitializedProperty); - const hasParameterPropertyAssignments = node.transformFlags & TransformFlags.ContainsParameterPropertyAssignments; const constructor = getFirstConstructorWithBody(node); + const hasInstancePropertyWithInitializer = forEach(node.members, isInstanceInitializedProperty); + const hasParameterPropertyAssignments = constructor && + constructor.transformFlags & TransformFlags.ContainsTypeScriptClassSyntax && + forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 4ddda98a41f..c2215b22ebf 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -11,52 +11,24 @@ namespace ts { message(diag: DiagnosticMessage, ...args: string[]): void; } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - export interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - diagnostics?: FileMap; // TODO(shkamat): this should be really be diagnostics but thats for later time - - invalidateProject(project: ResolvedConfigFileName, dependencyGraph: DependencyGraph | undefined): void; - getNextInvalidatedProject(): ResolvedConfigFileName | undefined; - hasPendingInvalidatedProjects(): boolean; - missingRoots: Map; - } - - type Mapper = ReturnType; interface DependencyGraph { buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; + /** value in config File map is true if project is referenced using prepend */ + referencingProjectsMap: ConfigFileMap>; } - export interface BuildOptions { + export interface BuildOptions extends OptionsBase { dry?: boolean; force?: boolean; verbose?: boolean; + /*@internal*/ clean?: boolean; /*@internal*/ watch?: boolean; /*@internal*/ help?: boolean; + preserveWatchOutput?: boolean; + listEmittedFiles?: boolean; + listFiles?: boolean; } enum BuildResultFlags { @@ -76,8 +48,9 @@ namespace ts { SyntaxErrors = 1 << 3, TypeErrors = 1 << 4, DeclarationEmitErrors = 1 << 5, + EmitErrors = 1 << 6, - AnyErrors = ConfigFileErrors | SyntaxErrors | TypeErrors | DeclarationEmitErrors + AnyErrors = ConfigFileErrors | SyntaxErrors | TypeErrors | DeclarationEmitErrors | EmitErrors } export enum UpToDateStatusType { @@ -94,6 +67,7 @@ namespace ts { OutOfDateWithUpstream, UpstreamOutOfDate, UpstreamBlocked, + ComputingUpstream, /** * Projects with no outputs (i.e. "solution" files) @@ -109,6 +83,7 @@ namespace ts { | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked + | Status.ComputingUpstream | Status.ContainerOnly; export namespace Status { @@ -178,6 +153,13 @@ namespace ts { upstreamProjectName: string; } + /** + * Computing status of upstream projects referenced + */ + export interface ComputingUpstream { + type: UpToDateStatusType.ComputingUpstream; + } + /** * One or more of the project's outputs is older than the newest output of * an upstream project. @@ -189,120 +171,90 @@ namespace ts { } } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; + interface FileMap { + setValue(fileName: U, value: T): void; + getValue(fileName: U): T | undefined; + hasKey(fileName: U): boolean; + removeKey(fileName: U): void; + forEach(action: (value: T, key: V) => void): void; getSize(): number; + clear(): void; } + type ResolvedConfigFilePath = ResolvedConfigFileName & Path; + type ConfigFileMap = FileMap; + type ToResolvedConfigFilePath = (fileName: ResolvedConfigFileName) => ResolvedConfigFilePath; + type ToPath = (fileName: string) => Path; + /** * A FileMap maintains a normalized-key to value relationship */ - function createFileMap(): FileMap { + function createFileMap(toPath: ToResolvedConfigFilePath): ConfigFileMap; + function createFileMap(toPath: ToPath): FileMap; + function createFileMap(toPath: (fileName: U) => V): FileMap { // tslint:disable-next-line:no-null-keyword const lookup = createMap(); return { setValue, getValue, - getValueOrUndefined, removeKey, - getKeys, + forEach, hasKey, - getSize + getSize, + clear }; - function getKeys(): string[] { - return Object.keys(lookup); + function forEach(action: (value: T, key: V) => void) { + lookup.forEach(action); } - function hasKey(fileName: string) { - return lookup.has(normalizePath(fileName)); + function hasKey(fileName: U) { + return lookup.has(toPath(fileName)); } - function removeKey(fileName: string) { - lookup.delete(normalizePath(fileName)); + function removeKey(fileName: U) { + lookup.delete(toPath(fileName)); } - function setValue(fileName: string, value: T) { - lookup.set(normalizePath(fileName), value); + function setValue(fileName: U, value: T) { + lookup.set(toPath(fileName), value); } - function getValue(fileName: string): T | never { - const f = normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f)!; - } - else { - throw new Error(`No value corresponding to ${fileName} exists in this map`); - } - } - - function getValueOrUndefined(fileName: string): T | undefined { - const f = normalizePath(fileName); - return lookup.get(f); + function getValue(fileName: U): T | undefined { + return lookup.get(toPath(fileName)); } function getSize() { return lookup.size; } + + function clear() { + lookup.clear(); + } } - function createDependencyMapper() { - const childToParents = createFileMap(); - const parentToChildren = createFileMap(); - const allKeys = createFileMap(); - - function addReference(childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName): void { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap: ConfigFileMap, resolved: ResolvedConfigFileName, createT: () => T): T { + const existingValue = configFileMap.getValue(resolved); + let newValue: T | undefined; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - - function getReferencesTo(parentConfigFileName: ResolvedConfigFileName): ResolvedConfigFileName[] { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - - function getReferencesOf(childConfigFileName: ResolvedConfigFileName): ResolvedConfigFileName[] { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - - function getKeys(): ReadonlyArray { - return allKeys.getKeys() as ResolvedConfigFileName[]; - } - - function addEntry(mapToAddTo: typeof childToParents | typeof parentToChildren, key: ResolvedConfigFileName, element: ResolvedConfigFileName) { - key = normalizePath(key) as ResolvedConfigFileName; - element = normalizePath(element) as ResolvedConfigFileName; - let arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - - return { - addReference, - getReferencesTo, - getReferencesOf, - getKeys - }; + return existingValue || newValue!; } - function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine) { + function getOrCreateValueMapFromConfigFileMap(configFileMap: ConfigFileMap>, resolved: ResolvedConfigFileName): Map { + return getOrCreateValueFromConfigFileMap>(configFileMap, resolved, createMap); + } + + export function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine) { const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true); const outputPath = resolvePath(configFile.options.declarationDir || configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath); return changeExtension(outputPath, Extension.Dts); } - function getOutputJavaScriptFileName(inputFileName: string, configFile: ParsedCommandLine) { + function getOutputJSFileName(inputFileName: string, configFile: ParsedCommandLine) { const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true); const outputPath = resolvePath(configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath); const newExtension = fileExtensionIs(inputFileName, Extension.Json) ? Extension.Json : @@ -317,7 +269,7 @@ namespace ts { } const outputs: string[] = []; - const js = getOutputJavaScriptFileName(inputFileName, configFile); + const js = getOutputJSFileName(inputFileName, configFile); outputs.push(js); if (configFile.options.sourceMap) { outputs.push(`${js}.map`); @@ -333,16 +285,17 @@ namespace ts { } function getOutFileOutputs(project: ParsedCommandLine): ReadonlyArray { - if (!project.options.outFile) { + const out = project.options.outFile || project.options.out; + if (!out) { return Debug.fail("outFile must be set"); } const outputs: string[] = []; - outputs.push(project.options.outFile); + outputs.push(out); if (project.options.sourceMap) { - outputs.push(`${project.options.outFile}.map`); + outputs.push(`${out}.map`); } if (getEmitDeclarations(project.options)) { - const dts = changeExtension(project.options.outFile, Extension.Dts); + const dts = changeExtension(out, Extension.Dts); outputs.push(dts); if (project.options.declarationMap) { outputs.push(`${dts}.map`); @@ -355,32 +308,6 @@ namespace ts { return opts.rootDir || getDirectoryPath(configFileName); } - function createConfigFileCache(host: CompilerHost) { - const cache = createFileMap(); - const configParseHost = parseConfigHostFromCompilerHost(host); - - function parseConfigFile(configFilePath: ResolvedConfigFileName) { - const sourceFile = host.getSourceFile(configFilePath, ScriptTarget.JSON) as JsonSourceFile; - if (sourceFile === undefined) { - return undefined; - } - - const parsed = parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - - function removeKey(configFilePath: ResolvedConfigFileName) { - cache.removeKey(configFilePath); - } - - return { - parseConfigFile, - removeKey - }; - } - function newer(date1: Date, date2: Date): Date { return date2 > date1 ? date2 : date1; } @@ -389,69 +316,6 @@ namespace ts { return fileExtensionIs(fileName, Extension.Dts); } - export function createBuildContext(options: BuildOptions): BuildContext { - const invalidatedProjectQueue = [] as ResolvedConfigFileName[]; - let nextIndex = 0; - const projectPendingBuild = createFileMap(); - const missingRoots = createMap(); - const diagnostics = options.watch ? createFileMap() : undefined; - - return { - options, - projectStatus: createFileMap(), - diagnostics, - unchangedOutputs: createFileMap(), - invalidateProject, - getNextInvalidatedProject, - hasPendingInvalidatedProjects, - missingRoots - }; - - function invalidateProject(proj: ResolvedConfigFileName, dependencyGraph: DependencyGraph | undefined) { - if (!projectPendingBuild.hasKey(proj)) { - addProjToQueue(proj); - if (dependencyGraph) { - queueBuildForDownstreamReferences(proj, dependencyGraph); - } - } - } - - function addProjToQueue(proj: ResolvedConfigFileName) { - Debug.assert(!projectPendingBuild.hasKey(proj)); - projectPendingBuild.setValue(proj, true); - invalidatedProjectQueue.push(proj); - } - - function getNextInvalidatedProject() { - if (nextIndex < invalidatedProjectQueue.length) { - const proj = invalidatedProjectQueue[nextIndex]; - nextIndex++; - projectPendingBuild.removeKey(proj); - if (!projectPendingBuild.getSize()) { - invalidatedProjectQueue.length = 0; - nextIndex = 0; - } - return proj; - } - } - - function hasPendingInvalidatedProjects() { - return !!projectPendingBuild.getSize(); - } - - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root: ResolvedConfigFileName, dependencyGraph: DependencyGraph) { - const deps = dependencyGraph.dependencyMap.getReferencesTo(root); - for (const ref of deps) { - // Can skip circular references - if (!projectPendingBuild.hasKey(ref)) { - addProjToQueue(ref); - queueBuildForDownstreamReferences(ref, dependencyGraph); - } - } - } - } - export interface SolutionBuilderHost extends CompilerHost { getModifiedTime(fileName: string): Date | undefined; setModifiedTime(fileName: string, date: Date): void; @@ -464,6 +328,22 @@ namespace ts { export interface SolutionBuilderWithWatchHost extends SolutionBuilderHost, WatchHost { } + export interface SolutionBuilder { + buildAllProjects(): ExitStatus; + cleanAllProjects(): ExitStatus; + + /*@internal*/ resolveProjectName(name: string): ResolvedConfigFileName; + /*@internal*/ getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus; + /*@internal*/ getBuildGraph(configFileNames: ReadonlyArray): DependencyGraph; + + /*@internal*/ invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel): void; + /*@internal*/ buildInvalidatedProject(): void; + + /*@internal*/ resetBuildContext(opts?: BuildOptions): void; + + /*@internal*/ startWatching(): void; + } + /** * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic */ @@ -496,23 +376,55 @@ namespace ts { return host; } + function getCompilerOptionsOfBuildOptions(buildOptions: BuildOptions): CompilerOptions { + const result = {} as CompilerOptions; + commonOptionsWithBuild.forEach(option => { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references * TODO: use SolutionBuilderWithWatchHost => watchedSolution * use SolutionBuilderHost => Solution */ - export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions) { + export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilder { const hostWithWatch = host as SolutionBuilderWithWatchHost; - const configFileCache = createConfigFileCache(host); - let context = createBuildContext(defaultOptions); + const currentDirectory = host.getCurrentDirectory(); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + const parseConfigFileHost = parseConfigHostFromCompilerHost(host); + + // State of the solution + let options = defaultOptions; + let baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + type ConfigFileCacheEntry = ParsedCommandLine | Diagnostic; + const configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + const unchangedOutputs = createFileMap(toPath as ToPath); + /** Map from config file name to up-to-date status */ + const projectStatus = createFileMap(toPath); + const missingRoots = createMap(); + let globalDependencyGraph: DependencyGraph | undefined; + const writeFileName = (s: string) => host.trace && host.trace(s); + + // Watch state + const diagnostics = createFileMap>(toPath); + const projectPendingBuild = createFileMap(toPath); + const projectErrorsReported = createFileMap(toPath); + const invalidatedProjectQueue = [] as ResolvedConfigFileName[]; + let nextProjectToBuild = 0; let timerToBuildInvalidatedProject: any; let reportFileChangeDetected = false; - const existingWatchersForWildcards = createMap(); + // Watches for the solution + const allWatchedWildcardDirectories = createFileMap>(toPath); + const allWatchedInputFiles = createFileMap>(toPath); + const allWatchedConfigFiles = createFileMap(toPath); + return { buildAllProjects, - getUpToDateStatus, getUpToDateStatusOfFile, cleanAllProjects, resetBuildContext, @@ -526,87 +438,176 @@ namespace ts { startWatching }; + function toPath(fileName: ResolvedConfigFileName): ResolvedConfigFilePath; + function toPath(fileName: string): Path; + function toPath(fileName: string) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + + function resetBuildContext(opts = defaultOptions) { + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + clearMap(allWatchedWildcardDirectories, wildCardWatches => clearMap(wildCardWatches, closeFileWatcherOf)); + clearMap(allWatchedInputFiles, inputFileWatches => clearMap(inputFileWatches, closeFileWatcher)); + clearMap(allWatchedConfigFiles, closeFileWatcher); + } + + function isParsedCommandLine(entry: ConfigFileCacheEntry): entry is ParsedCommandLine { + return !!(entry as ParsedCommandLine).options; + } + + function parseConfigFile(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined { + const value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + + let diagnostic: Diagnostic | undefined; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = d => diagnostic = d; + const parsed = getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop; + configFileCache.setValue(configFilePath, parsed || diagnostic!); + return parsed; + } + function reportStatus(message: DiagnosticMessage, ...args: string[]) { host.reportSolutionBuilderStatus(createCompilerDiagnostic(message, ...args)); } - function storeErrors(proj: ResolvedConfigFileName, diagnostics: ReadonlyArray) { - if (context.options.watch) { - storeErrorSummary(proj, diagnostics.filter(diagnostic => diagnostic.category === DiagnosticCategory.Error).length); - } - } - - function storeErrorSummary(proj: ResolvedConfigFileName, errorCount: number) { - if (context.options.watch) { - context.diagnostics!.setValue(proj, errorCount); - } - } - function reportWatchStatus(message: DiagnosticMessage, ...args: (string | number | undefined)[]) { if (hostWithWatch.onWatchStatusChange) { - hostWithWatch.onWatchStatusChange(createCompilerDiagnostic(message, ...args), host.getNewLine(), { preserveWatchOutput: context.options.preserveWatchOutput }); + hostWithWatch.onWatchStatusChange(createCompilerDiagnostic(message, ...args), host.getNewLine(), baseCompilerOptions); } } function startWatching() { - const graph = getGlobalDependencyGraph()!; - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - + const graph = getGlobalDependencyGraph(); for (const resolved of graph.buildQueue) { - const cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - hostWithWatch.watchFile(resolved, () => { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); + // Watch this file + watchConfigFile(resolved); + const cfg = parseConfigFile(resolved); + if (cfg) { // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - updateWatchingWildcardDirectories(existingWatchersForWildcards, createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), (dir, flags) => { - return hostWithWatch.watchDirectory(dir, () => { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & WatchDirectoryFlags.Recursive)); - }); - } + watchWildCardDirectories(resolved, cfg); // Watch input files - for (const input of cfg.fileNames) { - hostWithWatch.watchFile(input, () => { - invalidateProjectAndScheduleBuilds(resolved); - }); - } + watchInputFiles(resolved, cfg); } } } - function invalidateProjectAndScheduleBuilds(resolved: ResolvedConfigFileName) { + function watchConfigFile(resolved: ResolvedConfigFileName) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, () => { + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Full); + })); + } + } + + function watchWildCardDirectories(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { + if (!options.watch) return; + updateWatchingWildcardDirectories( + getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), + createMapFromTemplate(parsed.configFileSpecs!.wildcardDirectories), + (dir, flags) => { + return hostWithWatch.watchDirectory(dir, fileOrDirectory => { + const fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Partial); + }, !!(flags & WatchDirectoryFlags.Recursive)); + } + ); + } + + function watchInputFiles(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { + if (!options.watch) return; + mutateMap( + getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), + arrayToMap(parsed.fileNames, toPath), + { + createNewValue: (_key, input) => hostWithWatch.watchFile(input, () => { + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.None); + }), + onDeleteValue: closeFileWatcher, + } + ); + } + + function isOutputFile(fileName: string, configFile: ParsedCommandLine) { + if (configFile.options.noEmit) return false; + + // ts or tsx files are not output + if (!fileExtensionIs(fileName, Extension.Dts) && + (fileExtensionIs(fileName, Extension.Ts) || fileExtensionIs(fileName, Extension.Tsx))) { + return false; + } + + // If options have --outFile or --out, check if its that + const out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, removeFileExtension(out) + Extension.Dts))) { + return true; + } + + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + + // If --outDir, check if file is in that directory + if (configFile.options.outDir && containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + + return !forEach(configFile.fileNames, inputFile => isSameFile(fileName, inputFile)); + } + + function isSameFile(file1: string, file2: string) { + return comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === Comparison.EqualTo; + } + + function invalidateProjectAndScheduleBuilds(resolved: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel) { reportFileChangeDetected = true; - invalidateProject(resolved); + invalidateResolvedProject(resolved, reloadLevel); scheduleBuildInvalidatedProject(); } - function resetBuildContext(opts = defaultOptions) { - context = createBuildContext(opts); - } - function getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames: ReadonlyArray) { - const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) return undefined; - - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project: ParsedCommandLine | undefined): UpToDateStatus { @@ -614,13 +615,13 @@ namespace ts { return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; } - const prior = context.projectStatus.getValueOrUndefined(project.options.configFilePath!); + const prior = projectStatus.getValue(project.options.configFilePath as ResolvedConfigFilePath); if (prior !== undefined) { return prior; } const actual = getUpToDateStatusWorker(project); - context.projectStatus.setValue(project.options.configFilePath!, actual); + projectStatus.setValue(project.options.configFilePath as ResolvedConfigFilePath, actual); return actual; } @@ -691,7 +692,7 @@ namespace ts { // had its file touched but not had its contents changed - this allows us // to skip a downstream typecheck if (isDeclarationFile(output)) { - const unchangedTime = context.unchangedOutputs.getValueOrUndefined(output); + const unchangedTime = unchangedOutputs.getValue(output); if (unchangedTime !== undefined) { newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } @@ -706,10 +707,16 @@ namespace ts { let usesPrepend = false; let upstreamChangedProject: string | undefined; if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath as ResolvedConfigFileName, { type: UpToDateStatusType.ComputingUpstream }); for (const ref of project.projectReferences) { usesPrepend = usesPrepend || !!(ref.prepend); - const resolvedRef = resolveProjectReferencePath(host, ref); - const refStatus = getUpToDateStatus(configFileCache.parseConfigFile(resolvedRef)); + const resolvedRef = resolveProjectReferencePath(ref); + const refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } // An upstream project is blocked if (refStatus.type === UpToDateStatusType.Unbuildable) { @@ -786,24 +793,53 @@ namespace ts { }; } - function invalidateProject(configFileName: string) { - const resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist + function invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } - // TODO: do those things - return; + function invalidateResolvedProject(resolved: ResolvedConfigFileName, reloadLevel?: ConfigFileProgramReloadLevel) { + if (reloadLevel === ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); } - configFileCache.removeKey(resolved); - context.projectStatus.removeKey(resolved); - if (context.options.watch) { - context.diagnostics!.removeKey(resolved); - } + addProjToQueue(resolved, reloadLevel); + } - context.invalidateProject(resolved, getGlobalDependencyGraph()); + /** + * return true if new addition + */ + function addProjToQueue(proj: ResolvedConfigFileName, reloadLevel?: ConfigFileProgramReloadLevel) { + const value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); + } + } + + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + const project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + const reloadLevel = projectPendingBuild.getValue(project)!; + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project, reloadLevel }; + } + } + + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); } function scheduleBuildInvalidatedProject() { @@ -820,134 +856,148 @@ namespace ts { timerToBuildInvalidatedProject = undefined; if (reportFileChangeDetected) { reportFileChangeDetected = false; + projectErrorsReported.clear(); reportWatchStatus(Diagnostics.File_change_detected_Starting_incremental_compilation); } - const buildProject = context.getNextInvalidatedProject(); - buildSomeProjects(p => p === buildProject); - if (context.hasPendingInvalidatedProjects()) { - if (!timerToBuildInvalidatedProject) { - scheduleBuildInvalidatedProject(); + const buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); } - } - else { - reportErrorSummary(); } } function reportErrorSummary() { - if (context.options.watch) { - let errorCount = 0; - context.diagnostics!.getKeys().forEach(resolved => errorCount += context.diagnostics!.getValue(resolved)); - reportWatchStatus(errorCount === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount); + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(project => { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || emptyArray); + } + }); + let totalErrors = 0; + diagnostics.forEach(singleProjectErrors => totalErrors += singleProjectErrors.filter(diagnostic => diagnostic.category === DiagnosticCategory.Error).length); + reportWatchStatus(totalErrors === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors); } } - function buildSomeProjects(predicate: (projName: ResolvedConfigFileName) => boolean) { - const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(rootNames); - if (resolvedNames === undefined) return; + function buildSingleInvalidatedProject(resolved: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel) { + const proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } - const graph = createDependencyGraph(resolvedNames)!; - for (const next of graph.buildQueue) { - if (!predicate(next)) continue; + if (reloadLevel === ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ConfigFileProgramReloadLevel.Partial) { + // Update file names + const result = getFileNamesFromConfigSpecs(proj.configFileSpecs!, getDirectoryPath(resolved), proj.options, parseConfigFileHost); + updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs!, proj.errors, canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } - const resolved = resolveProjectName(next); - if (!resolved) continue; // ?? - const proj = configFileCache.parseConfigFile(resolved); - if (!proj) continue; // ? + const status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); - const status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + const buildResult = buildSingleProject(resolved); + const dependencyGraph = getGlobalDependencyGraph(); + const referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; + // Always use build order to queue projects + for (const project of dependencyGraph.buildQueue) { + const prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - - buildSingleProject(next); } } - function createDependencyGraph(roots: ResolvedConfigFileName[]): DependencyGraph | undefined { - const temporaryMarks: { [path: string]: true } = {}; - const permanentMarks: { [path: string]: true } = {}; + function createDependencyGraph(roots: ResolvedConfigFileName[]): DependencyGraph { + const temporaryMarks = createFileMap(toPath); + const permanentMarks = createFileMap(toPath); const circularityReportStack: string[] = []; const buildOrder: ResolvedConfigFileName[] = []; - const graph = createDependencyMapper(); - - let hadError = false; - + const referencingProjectsMap = createFileMap>(toPath); for (const root of roots) { visit(root); } - if (hadError) { - return undefined; - } - return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap }; - function visit(projPath: ResolvedConfigFileName, inCircularContext = false) { + function visit(projPath: ResolvedConfigFileName, inCircularContext?: boolean) { // Already visited - if (permanentMarks[projPath]) return; + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - // TODO(shkamat): Account for this error + // TODO:: Do we report this as error? reportStatus(Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; } - } - - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - const parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + const parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (const ref of parsed.projectReferences) { const resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + const referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, () => createFileMap(toPath)); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } + function buildSingleProject(proj: ResolvedConfigFileName): BuildResultFlags { - if (context.options.dry) { + if (options.dry) { reportStatus(Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) reportStatus(Diagnostics.Building_project_0, proj); + if (options.verbose) reportStatus(Diagnostics.Building_project_0, proj); let resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - const configFile = configFileCache.parseConfigFile(proj); + const configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - storeErrorSummary(proj, 1); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } - if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } @@ -956,7 +1006,8 @@ namespace ts { projectReferences: configFile.projectReferences, host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; const program = createProgram(programOptions); @@ -966,53 +1017,36 @@ namespace ts { ...program.getConfigFileParsingDiagnostics(), ...program.getSyntacticDiagnostics()]; if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (const diag of syntaxDiagnostics) { - host.reportDiagnostic(diag); - } - storeErrors(proj, syntaxDiagnostics); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (getEmitDeclarations(program.getCompilerOptions())) { const declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (const diag of declDiagnostics) { - host.reportDiagnostic(diag); - } - storeErrors(proj, declDiagnostics); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics const semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (const diag of semanticDiagnostics) { - host.reportDiagnostic(diag); - } - storeErrors(proj, semanticDiagnostics); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } let newestDeclarationFileContentChangedTime = minimumDate; let anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, (fileName, content, writeBom, onError) => { + let emitDiagnostics: Diagnostic[] | undefined; + const reportEmitDiagnostic = (d: Diagnostic) => (emitDiagnostics || (emitDiagnostics = [])).push(d); + emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, (fileName, content, writeBom, onError) => { let priorChangeTime: Date | undefined; - - if (!anyDtsChanged && isDeclarationFile(fileName) && host.fileExists(fileName)) { - if (host.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } @@ -1020,24 +1054,38 @@ namespace ts { host.writeFile(fileName, content, writeBom, onError, emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } + const status: UpToDateStatus = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + + function buildErrors(diagnostics: ReadonlyArray, errorFlags: BuildResultFlags, errorType: string) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: `${errorType} errors` }); + return resultFlags; + } } function updateOutputTimestamps(proj: ParsedCommandLine) { - if (context.options.dry) { + if (options.dry) { return reportStatus(Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath!); } - if (context.options.verbose) { + if (options.verbose) { reportStatus(Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath!); } @@ -1052,22 +1100,18 @@ namespace ts { host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath!, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); + projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); } - function getFilesToClean(configFileNames: ReadonlyArray): string[] | undefined { - const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) return undefined; - + function getFilesToClean(): string[] { // Get the same graph for cleaning we'd use for building - const graph = createDependencyGraph(resolvedNames); - if (graph === undefined) return undefined; - + const graph = getGlobalDependencyGraph(); const filesToDelete: string[] = []; for (const proj of graph.buildQueue) { - const parsed = configFileCache.parseConfigFile(proj); + const parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } const outputs = getAllProjectOutputs(parsed); @@ -1080,28 +1124,9 @@ namespace ts { return filesToDelete; } - function getAllProjectsInScope(): ReadonlyArray | undefined { - const resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) return undefined; - const graph = createDependencyGraph(resolvedNames); - if (graph === undefined) return undefined; - return graph.buildQueue; - } - function cleanAllProjects() { - const resolvedNames: ReadonlyArray | undefined = getAllProjectsInScope(); - if (resolvedNames === undefined) { - reportStatus(Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - - const filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - reportStatus(Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - - if (context.options.dry) { + const filesToDelete = getFilesToClean(); + if (options.dry) { reportStatus(Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(f => `\r\n * ${f}`).join("")); return ExitStatus.Success; } @@ -1113,55 +1138,35 @@ namespace ts { return ExitStatus.Success; } - function resolveProjectName(name: string): ResolvedConfigFileName | undefined { - const fullPath = resolvePath(host.getCurrentDirectory(), name); - if (host.fileExists(fullPath)) { - return fullPath as ResolvedConfigFileName; - } - const fullPathWithTsconfig = combinePaths(fullPath, "tsconfig.json"); - if (host.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig as ResolvedConfigFileName; - } - // TODO(shkamat): right now this is accounted as 1 error in config file, but we need to do better - host.reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_0_not_found, relName(fullPath))); - return undefined; + function resolveProjectName(name: string): ResolvedConfigFileName { + return resolveConfigFileProjectName(resolvePath(host.getCurrentDirectory(), name)); } - function resolveProjectNames(configFileNames: ReadonlyArray): ResolvedConfigFileName[] | undefined { - const resolvedNames: ResolvedConfigFileName[] = []; - for (const name of configFileNames) { - const resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + function resolveProjectNames(configFileNames: ReadonlyArray): ResolvedConfigFileName[] { + return configFileNames.map(resolveProjectName); } function buildAllProjects(): ExitStatus { - if (context.options.watch) { reportWatchStatus(Diagnostics.Starting_compilation_in_watch_mode); } + if (options.watch) { reportWatchStatus(Diagnostics.Starting_compilation_in_watch_mode); } const graph = getGlobalDependencyGraph(); - if (graph === undefined) { - reportErrorSummary(); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - - const queue = graph.buildQueue; reportBuildQueue(graph); - let anyFailed = false; - for (const next of queue) { - const proj = configFileCache.parseConfigFile(next); + for (const next of graph.buildQueue) { + const proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + + // report errors early when using continue or break statements + const errors = proj.errors; const status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); const projName = proj.options.configFilePath!; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact @@ -1170,18 +1175,21 @@ namespace ts { continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } @@ -1193,17 +1201,29 @@ namespace ts { return anyFailed ? ExitStatus.DiagnosticsPresent_OutputsSkipped : ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj: ResolvedConfigFileName) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj) as Diagnostic]); + } + + function reportAndStoreErrors(proj: ResolvedConfigFileName, errors: ReadonlyArray) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + + function reportErrors(errors: ReadonlyArray) { + errors.forEach(err => host.reportDiagnostic(err)); + } + /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph: DependencyGraph) { - if (!context.options.verbose) return; - - const names: string[] = []; - for (const name of graph.buildQueue) { - names.push(name); + if (options.verbose) { + reportStatus(Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(s => "\r\n * " + relName(s)).join("")); } - if (context.options.verbose) reportStatus(Diagnostics.Projects_in_this_build_Colon_0, names.map(s => "\r\n * " + relName(s)).join("")); } function relName(path: string): string { @@ -1214,13 +1234,21 @@ namespace ts { * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName: string, status: UpToDateStatus) { - if (!context.options.verbose) return; + if (!options.verbose) return; return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } + export function resolveConfigFileProjectName(project: string): ResolvedConfigFileName { + if (fileExtensionIs(project, Extension.Json)) { + return project as ResolvedConfigFileName; + } + + return combinePaths(project, "tsconfig.json") as ResolvedConfigFileName; + } + export function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -1274,6 +1302,8 @@ namespace ts { status.reason); case UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: assertType(status); diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index 20b97c1b778..4822f1dc06a 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -9,6 +9,7 @@ "files": [ "core.ts", "performance.ts", + "semver.ts", "types.ts", "sys.ts", @@ -51,6 +52,7 @@ "resolutionCache.ts", "moduleSpecifiers.ts", "watch.ts", - "tsbuild.ts" + "tsbuild.ts", + "inspectValue.ts", ] } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 279fef73d5e..f2c9238aace 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -24,7 +24,84 @@ namespace ts { | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral - | SyntaxKind.Unknown; + | SyntaxKind.Unknown + | KeywordSyntaxKind; + + export type KeywordSyntaxKind = + | SyntaxKind.AbstractKeyword + | SyntaxKind.AnyKeyword + | SyntaxKind.AsKeyword + | SyntaxKind.BooleanKeyword + | SyntaxKind.BreakKeyword + | SyntaxKind.CaseKeyword + | SyntaxKind.CatchKeyword + | SyntaxKind.ClassKeyword + | SyntaxKind.ContinueKeyword + | SyntaxKind.ConstKeyword + | SyntaxKind.ConstructorKeyword + | SyntaxKind.DebuggerKeyword + | SyntaxKind.DeclareKeyword + | SyntaxKind.DefaultKeyword + | SyntaxKind.DeleteKeyword + | SyntaxKind.DoKeyword + | SyntaxKind.ElseKeyword + | SyntaxKind.EnumKeyword + | SyntaxKind.ExportKeyword + | SyntaxKind.ExtendsKeyword + | SyntaxKind.FalseKeyword + | SyntaxKind.FinallyKeyword + | SyntaxKind.ForKeyword + | SyntaxKind.FromKeyword + | SyntaxKind.FunctionKeyword + | SyntaxKind.GetKeyword + | SyntaxKind.IfKeyword + | SyntaxKind.ImplementsKeyword + | SyntaxKind.ImportKeyword + | SyntaxKind.InKeyword + | SyntaxKind.InferKeyword + | SyntaxKind.InstanceOfKeyword + | SyntaxKind.InterfaceKeyword + | SyntaxKind.IsKeyword + | SyntaxKind.KeyOfKeyword + | SyntaxKind.LetKeyword + | SyntaxKind.ModuleKeyword + | SyntaxKind.NamespaceKeyword + | SyntaxKind.NeverKeyword + | SyntaxKind.NewKeyword + | SyntaxKind.NullKeyword + | SyntaxKind.NumberKeyword + | SyntaxKind.ObjectKeyword + | SyntaxKind.PackageKeyword + | SyntaxKind.PrivateKeyword + | SyntaxKind.ProtectedKeyword + | SyntaxKind.PublicKeyword + | SyntaxKind.ReadonlyKeyword + | SyntaxKind.RequireKeyword + | SyntaxKind.GlobalKeyword + | SyntaxKind.ReturnKeyword + | SyntaxKind.SetKeyword + | SyntaxKind.StaticKeyword + | SyntaxKind.StringKeyword + | SyntaxKind.SuperKeyword + | SyntaxKind.SwitchKeyword + | SyntaxKind.SymbolKeyword + | SyntaxKind.ThisKeyword + | SyntaxKind.ThrowKeyword + | SyntaxKind.TrueKeyword + | SyntaxKind.TryKeyword + | SyntaxKind.TypeKeyword + | SyntaxKind.TypeOfKeyword + | SyntaxKind.UndefinedKeyword + | SyntaxKind.UniqueKeyword + | SyntaxKind.UnknownKeyword + | SyntaxKind.VarKeyword + | SyntaxKind.VoidKeyword + | SyntaxKind.WhileKeyword + | SyntaxKind.WithKeyword + | SyntaxKind.YieldKeyword + | SyntaxKind.AsyncKeyword + | SyntaxKind.AwaitKeyword + | SyntaxKind.OfKeyword; export type JsxTokenSyntaxKind = | SyntaxKind.LessThanSlashToken @@ -1708,7 +1785,7 @@ namespace ts { export interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } @@ -2551,7 +2628,18 @@ namespace ts { fileName: string; /* @internal */ path: Path; text: string; + /** Resolved path can be different from path property, + * when file is included through project reference is mapped to its output instead of source + * in that case resolvedPath = path to output file + * path = input file's path + */ /* @internal */ resolvedPath: Path; + /** Original file name that can be different from fileName, + * when file is included through project reference is mapped to its output instead of source + * in that case originalFileName = name of input file + * fileName = output file's name + */ + /* @internal */ originalFileName: string; /** * If two source files are for the same version of the same package, one will redirect to the other. @@ -2593,6 +2681,8 @@ namespace ts { /* @internal */ externalModuleIndicator?: Node; // The first node that causes this file to be a CommonJS module /* @internal */ commonJsModuleIndicator?: Node; + // JS identifier-declarations that are intended to merge with globals + /* @internal */ jsGlobalAugmentations?: SymbolTable; /* @internal */ identifiers: Map; // Map from a string to an interned string /* @internal */ nodeCount: number; @@ -2815,7 +2905,9 @@ namespace ts { /* @internal */ getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + /*@internal*/ getProjectReferenceRedirect(fileName: string): string | undefined; } /* @internal */ @@ -2893,7 +2985,7 @@ namespace ts { } /* @internal */ - export interface TypeCheckerHost { + export interface TypeCheckerHost extends ModuleSpecifierResolutionHost { getCompilerOptions(): CompilerOptions; getSourceFiles(): ReadonlyArray; @@ -3011,8 +3103,6 @@ namespace ts { getExportsOfModule(moduleSymbol: Symbol): Symbol[]; /** Unlike `getExportsOfModule`, this includes properties of an `export =` value. */ /* @internal */ getExportsAndPropertiesOfModule(moduleSymbol: Symbol): Symbol[]; - - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; @@ -3034,8 +3124,8 @@ namespace ts { /* @internal */ getStringType(): Type; /* @internal */ getNumberType(): Type; /* @internal */ getBooleanType(): Type; - /* @internal */ getFalseType(): Type; - /* @internal */ getTrueType(): Type; + /* @internal */ getFalseType(fresh?: boolean): Type; + /* @internal */ getTrueType(fresh?: boolean): Type; /* @internal */ getVoidType(): Type; /* @internal */ getUndefinedType(): Type; /* @internal */ getNullType(): Type; @@ -3079,7 +3169,7 @@ namespace ts { * True if `contextualType` should not be considered for completions because * e.g. it specifies `kind: "a"` and obj has `kind: "b"`. */ - /* @internal */ isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression): boolean; + /* @internal */ isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes): boolean; /** * For a union, will include a property if it's defined in *any* of the member types. * So for `{ a } | { b }`, this will include both `a` and `b`. @@ -3168,6 +3258,8 @@ namespace ts { InTypeAlias = 1 << 23, // Writing type in type alias declaration InInitialEntityName = 1 << 24, // Set when writing the LHS of an entity name or entity name expression InReverseMappedType = 1 << 25, + + /* @internal */ DoNotIncludeSymbolChain = 1 << 26, // Skip looking up and printing an accessible symbol chain } // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment @@ -3230,6 +3322,9 @@ namespace ts { // Prefer aliases which are not directly visible UseAliasDefinedOutsideCurrentScope = 0x00000008, + + // Skip building an accessible symbol chain + /* @internal */ DoNotIncludeSymbolChain = 0x00000010, } /* @internal */ @@ -3383,7 +3478,7 @@ namespace ts { isImplementationOfOverload(node: FunctionLike): boolean | undefined; isRequiredInitializedParameter(node: ParameterDeclaration): boolean; isOptionalUninitializedParameterProperty(node: ParameterDeclaration): boolean; - isJSContainerFunctionDeclaration(node: FunctionDeclaration): boolean; + isExpandoFunctionDeclaration(node: FunctionDeclaration): boolean; getPropertiesOfContainerFunction(node: Declaration): Symbol[]; createTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration | PropertyAccessExpression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker, addUndefined?: boolean): TypeNode | undefined; createReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined; @@ -3405,6 +3500,7 @@ namespace ts { getJsxFactoryEntity(location?: Node): EntityName | undefined; getAllAccessorDeclarations(declaration: AccessorDeclaration): AllAccessorDeclarations; getSymbolOfExternalModuleSpecifier(node: StringLiteralLike): Symbol | undefined; + isBindingCapturedByNode(node: Node, decl: VariableDeclaration | BindingElement): boolean; } export const enum SymbolFlags { @@ -3435,7 +3531,7 @@ namespace ts { ExportStar = 1 << 23, // Export * declaration Optional = 1 << 24, // Optional property Transient = 1 << 25, // Transient symbol (created during type check) - JSContainer = 1 << 26, // Contains Javascript special declarations + Assignment = 1 << 26, // Assignment treated as declaration (eg `this.prop = 1`) ModuleExports = 1 << 27, // Symbol for CommonJS `module` of `module.exports` /* @internal */ @@ -3444,8 +3540,8 @@ namespace ts { Enum = RegularEnum | ConstEnum, Variable = FunctionScopedVariable | BlockScopedVariable, - Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor | JSContainer, - Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias | JSContainer, + Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor | Assignment, + Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias | Assignment, Namespace = ValueModule | NamespaceModule | Enum, Module = ValueModule | NamespaceModule, Accessor = GetAccessor | SetAccessor, @@ -3466,7 +3562,7 @@ namespace ts { InterfaceExcludes = Type & ~(Interface | Class), RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums - ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule | JSContainer), + ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule | Assignment), NamespaceModuleExcludes = 0, MethodExcludes = Value & ~Method, GetAccessorExcludes = Value & ~SetAccessor, @@ -3520,6 +3616,7 @@ namespace ts { type?: Type; // Type of value symbol uniqueESSymbolType?: Type; // UniqueESSymbol type for a symbol declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter + resolvedJSDocType?: Type; // Resolved type of a JSDoc type reference typeParameters?: TypeParameter[]; // Type parameters of type alias (undefined if non-generic) outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type inferredClassType?: Type; // Type of an inferred ES5 class @@ -3653,22 +3750,23 @@ namespace ts { EnumValuesComputed = 0x00004000, // Values for enum members have been computed, and any errors have been reported for them. LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration. LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure - CapturedBlockScopedBinding = 0x00020000, // Block-scoped binding that is captured in some function - BlockScopedBindingInLoop = 0x00040000, // Block-scoped binding with declaration nested inside iteration statement - ClassWithBodyScopedClassBinding = 0x00080000, // Decorated class that contains a binding to itself inside of the class body. - BodyScopedClassBinding = 0x00100000, // Binding to a decorated class inside of the class's body. - NeedsLoopOutParameter = 0x00200000, // Block scoped binding whose value should be explicitly copied outside of the converted loop - AssignmentsMarked = 0x00400000, // Parameter assignments have been marked - ClassWithConstructorReference = 0x00800000, // Class that contains a binding to its constructor inside of the class body. - ConstructorReferenceInClass = 0x01000000, // Binding to a class constructor inside of the class's body. + ContainsCapturedBlockScopeBinding = 0x00020000, // Part of a loop that contains block scoped variable captured in closure + CapturedBlockScopedBinding = 0x00040000, // Block-scoped binding that is captured in some function + BlockScopedBindingInLoop = 0x00080000, // Block-scoped binding with declaration nested inside iteration statement + ClassWithBodyScopedClassBinding = 0x00100000, // Decorated class that contains a binding to itself inside of the class body. + BodyScopedClassBinding = 0x00200000, // Binding to a decorated class inside of the class's body. + NeedsLoopOutParameter = 0x00400000, // Block scoped binding whose value should be explicitly copied outside of the converted loop + AssignmentsMarked = 0x00800000, // Parameter assignments have been marked + ClassWithConstructorReference = 0x01000000, // Class that contains a binding to its constructor inside of the class body. + ConstructorReferenceInClass = 0x02000000, // Binding to a class constructor inside of the class's body. } /* @internal */ export interface NodeLinks { flags: NodeCheckFlags; // Set of flags specific to Node resolvedType?: Type; // Cached type of type node + resolvedEnumType?: Type; // Cached constraint type from enum jsdoc tag resolvedSignature?: Signature; // Cached signature of signature node or call expression - resolvedSignatures?: Map; // Cached signatures of jsx node resolvedSymbol?: Symbol; // Cached name resolution result resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate @@ -3684,6 +3782,8 @@ namespace ts { switchTypes?: Type[]; // Cached array of switch case expression types jsxNamespace?: Symbol | false; // Resolved jsx namespace symbol for this node contextFreeType?: Type; // Cached context-free type used by the first pass of inference; used when a function's return is partially contextually sensitive + deferredNodes?: Map; // Set of nodes whose checking has been deferred + capturedBlockScopeBindings?: Symbol[]; // Block-scoped bindings captured beneath this part of an IterationStatement } export const enum TypeFlags { @@ -3731,7 +3831,7 @@ namespace ts { Unit = Literal | UniqueESSymbol | Nullable, StringOrNumberLiteral = StringLiteral | NumberLiteral, /* @internal */ - StringOrNumberLiteralOrUnique = StringOrNumberLiteral | UniqueESSymbol, + StringOrNumberLiteralOrUnique = StringLiteral | NumberLiteral | UniqueESSymbol, /* @internal */ DefinitelyFalsy = StringLiteral | NumberLiteral | BooleanLiteral | Void | Undefined | Null, PossiblyFalsy = DefinitelyFalsy | String | Number | Boolean, @@ -3802,6 +3902,15 @@ namespace ts { intrinsicName: string; // Name of intrinsic type } + /* @internal */ + export interface FreshableIntrinsicType extends IntrinsicType { + freshType: IntrinsicType; // Fresh version of type + regularType: IntrinsicType; // Regular version of type + } + + /* @internal */ + export type FreshableType = LiteralType | FreshableIntrinsicType; + // String literal types (TypeFlags.StringLiteral) // Numeric literal types (TypeFlags.NumberLiteral) export interface LiteralType extends Type { @@ -3962,6 +4071,7 @@ namespace ts { templateType?: Type; modifiersType?: Type; resolvedApparentType?: Type; + instantiating?: boolean; } export interface EvolvingArrayType extends ObjectType { @@ -4219,7 +4329,7 @@ namespace ts { } /* @internal */ - export const enum SpecialPropertyAssignmentKind { + export const enum AssignmentDeclarationKind { None, /// exports.name = expr ExportsProperty, @@ -4402,6 +4512,7 @@ namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; // Always combine with strict property + strictBindCallApply?: boolean; // Always combine with strict property strictNullChecks?: boolean; // Always combine with strict property strictPropertyInitialization?: boolean; // Always combine with strict property stripInternal?: boolean; @@ -4516,7 +4627,6 @@ namespace ts { /* @internal */ export interface ConfigFileSpecs { filesSpecs: ReadonlyArray | undefined; - referencesSpecs: ReadonlyArray | undefined; /** * Present to report errors (user specified specs), validatedIncludeSpecs are used for file name matching */ @@ -4532,7 +4642,6 @@ namespace ts { export interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; /* @internal */ spec: ConfigFileSpecs; } @@ -4559,6 +4668,9 @@ namespace ts { showInSimplifiedHelpView?: boolean; category?: DiagnosticMessage; strictFlag?: true; // true if the option is one of the flag under strict + affectsSourceFile?: true; // true if we should recreate SourceFiles after this option changes + affectsModuleResolution?: true; // currently same effect as `affectsSourceFile` + affectsBindDiagnostics?: true; // true if this affects binding (currently same effect as `affectsSourceFile`) affectsSemanticDiagnostics?: true; // true if option affects semantic diagnostics } @@ -4878,25 +4990,21 @@ namespace ts { // Markers // - Flags used to indicate that a subtree contains a specific transformation. - ContainsDecorators = 1 << 12, - ContainsPropertyInitializer = 1 << 13, - ContainsLexicalThis = 1 << 14, - ContainsCapturedLexicalThis = 1 << 15, - ContainsLexicalThisInComputedPropertyName = 1 << 16, - ContainsDefaultValueAssignments = 1 << 17, - ContainsParameterPropertyAssignments = 1 << 18, - ContainsSpread = 1 << 19, - ContainsObjectSpread = 1 << 20, - ContainsRest = ContainsSpread, - ContainsObjectRest = ContainsObjectSpread, - ContainsComputedPropertyName = 1 << 21, - ContainsBlockScopedBinding = 1 << 22, - ContainsBindingPattern = 1 << 23, - ContainsYield = 1 << 24, - ContainsHoistedDeclarationOrCompletion = 1 << 25, - ContainsDynamicImport = 1 << 26, - Super = 1 << 27, - ContainsSuper = 1 << 28, + ContainsTypeScriptClassSyntax = 1 << 12, // Decorators, Property Initializers, Parameter Property Initializers + ContainsLexicalThis = 1 << 13, + ContainsCapturedLexicalThis = 1 << 14, + ContainsLexicalThisInComputedPropertyName = 1 << 15, + ContainsDefaultValueAssignments = 1 << 16, + ContainsRestOrSpread = 1 << 17, + ContainsObjectRestOrSpread = 1 << 18, + ContainsComputedPropertyName = 1 << 19, + ContainsBlockScopedBinding = 1 << 20, + ContainsBindingPattern = 1 << 21, + ContainsYield = 1 << 22, + ContainsHoistedDeclarationOrCompletion = 1 << 23, + ContainsDynamicImport = 1 << 24, + Super = 1 << 25, + ContainsSuper = 1 << 26, // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. @@ -4920,23 +5028,22 @@ namespace ts { OuterExpressionExcludes = TypeScript | ES2015 | DestructuringAssignment | Generator | HasComputedFlags, PropertyAccessExcludes = OuterExpressionExcludes | Super, NodeExcludes = PropertyAccessExcludes | ContainsSuper, - ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, - FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, - ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, - MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, - ClassExcludes = NodeExcludes | ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsParameterPropertyAssignments | ContainsLexicalThisInComputedPropertyName, - ModuleExcludes = NodeExcludes | ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion, + ArrowFunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread, + FunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread, + ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread, + MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread, + ClassExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName, + ModuleExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion, TypeExcludes = ~ContainsTypeScript, - ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName | ContainsObjectSpread, - ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpread, - VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRest, + ObjectLiteralExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName | ContainsObjectRestOrSpread, + ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsRestOrSpread, + VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRestOrSpread, ParameterExcludes = NodeExcludes, - CatchClauseExcludes = NodeExcludes | ContainsObjectRest, - BindingPatternExcludes = NodeExcludes | ContainsRest, + CatchClauseExcludes = NodeExcludes | ContainsObjectRestOrSpread, + BindingPatternExcludes = NodeExcludes | ContainsRestOrSpread, // Masks // - Additional bitmasks - TypeScriptClassSyntaxMask = ContainsParameterPropertyAssignments | ContainsPropertyInitializer | ContainsDecorators, ES2015FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments, } @@ -4954,7 +5061,7 @@ namespace ts { /* @internal */ export interface EmitNode { annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup. - flags: EmitFlags; // Flags that customize emit + flags: EmitFlags; // Flags that customize emit leadingComments?: SynthesizedComment[]; // Synthesized leading comments trailingComments?: SynthesizedComment[]; // Synthesized trailing comments commentRange?: TextRange; // The text range to use when emitting leading or trailing comments @@ -5314,6 +5421,7 @@ namespace ts { /*@internal*/ inlineSourceMap?: boolean; /*@internal*/ extendedDiagnostics?: boolean; /*@internal*/ onlyPrintJsDocStyle?: boolean; + /*@internal*/ neverAsciiEscape?: boolean; } /* @internal */ @@ -5351,7 +5459,7 @@ namespace ts { reportInaccessibleThisError?(): void; reportPrivateInBaseOfClassExpression?(propertyName: string): void; reportInaccessibleUniqueSymbolError?(): void; - moduleResolverHost?: EmitHost; + moduleResolverHost?: ModuleSpecifierResolutionHost & { getSourceFiles(): ReadonlyArray, getCommonSourceDirectory(): string }; trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void; trackExternalModuleSymbolOfImportTypeNode?(symbol: Symbol): void; } @@ -5585,15 +5693,15 @@ namespace ts { type ConcretePragmaSpecs = typeof commentPragmas; /* @internal */ - export type PragmaPsuedoMap = {[K in keyof ConcretePragmaSpecs]?: {arguments: PragmaArgumentType, range: CommentRange}}; + export type PragmaPseudoMap = {[K in keyof ConcretePragmaSpecs]?: {arguments: PragmaArgumentType, range: CommentRange}}; /* @internal */ - export type PragmaPsuedoMapEntry = {[K in keyof PragmaPsuedoMap]: {name: K, args: PragmaPsuedoMap[K]}}[keyof PragmaPsuedoMap]; + export type PragmaPseudoMapEntry = {[K in keyof PragmaPseudoMap]: {name: K, args: PragmaPseudoMap[K]}}[keyof PragmaPseudoMap]; /* @internal */ - export interface ReadonlyPragmaMap extends ReadonlyMap { - get(key: TKey): PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]; - forEach(action: (value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][], key: TKey) => void): void; + export interface ReadonlyPragmaMap extends ReadonlyMap { + get(key: TKey): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]; + forEach(action: (value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey) => void): void; } /** @@ -5602,10 +5710,10 @@ namespace ts { * in multiple places */ /* @internal */ - export interface PragmaMap extends Map, ReadonlyPragmaMap { - set(key: TKey, value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]): this; - get(key: TKey): PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]; - forEach(action: (value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][], key: TKey) => void): void; + export interface PragmaMap extends Map, ReadonlyPragmaMap { + set(key: TKey, value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]): this; + get(key: TKey): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]; + forEach(action: (value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey) => void): void; } export interface UserPreferences { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 7a128a41c69..acaabdab9c7 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -14,7 +14,6 @@ namespace ts { /* @internal */ namespace ts { - export const emptyArray: never[] = [] as never[]; export const resolvingEmptyArray: never[] = [] as never[]; export const emptyMap = createMap() as ReadonlyMap & ReadonlyPragmaMap; export const emptyUnderscoreEscapedMap: ReadonlyUnderscoreEscapedMap = emptyMap as ReadonlyUnderscoreEscapedMap; @@ -102,22 +101,8 @@ namespace ts { } export function changesAffectModuleResolution(oldOptions: CompilerOptions, newOptions: CompilerOptions): boolean { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || moduleResolutionOptionDeclarations.some(o => + !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o))); } /** @@ -250,6 +235,12 @@ namespace ts { sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } + export function projectReferenceIsEqualTo(oldRef: ProjectReference, newRef: ProjectReference) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + export function moduleResolutionIsEqualTo(oldResolution: ResolvedModuleFull, newResolution: ResolvedModuleFull): boolean { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -533,14 +524,14 @@ namespace ts { return emitNode && emitNode.flags || 0; } - export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile) { + export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, neverAsciiEscape: boolean | undefined) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(isNumericLiteral(node) && node.numericLiteralFlags & TokenFlags.ContainsSeparator)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - const escapeText = getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? escapeString : escapeNonAsciiString; + const escapeText = neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. @@ -987,6 +978,7 @@ namespace ts { case SyntaxKind.StringKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: + case SyntaxKind.ObjectKeyword: case SyntaxKind.UndefinedKeyword: case SyntaxKind.NeverKeyword: return true; @@ -1679,15 +1671,15 @@ namespace ts { return node.kind === SyntaxKind.ImportEqualsDeclaration && (node).moduleReference.kind !== SyntaxKind.ExternalModuleReference; } - export function isSourceFileJavaScript(file: SourceFile): boolean { - return isInJavaScriptFile(file); + export function isSourceFileJS(file: SourceFile): boolean { + return isInJSFile(file); } - export function isSourceFileNotJavaScript(file: SourceFile): boolean { - return !isInJavaScriptFile(file); + export function isSourceFileNotJS(file: SourceFile): boolean { + return !isInJSFile(file); } - export function isInJavaScriptFile(node: Node | undefined): boolean { + export function isInJSFile(node: Node | undefined): boolean { return !!node && !!(node.flags & NodeFlags.JavaScriptFile); } @@ -1739,14 +1731,14 @@ namespace ts { return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === CharacterCodes.doubleQuote; } - export function getDeclarationOfJSInitializer(node: Node): Node | undefined { + export function getDeclarationOfExpando(node: Node): Node | undefined { if (!node.parent) { return undefined; } let name: Expression | BindingName | undefined; let decl: Node | undefined; if (isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -1771,7 +1763,7 @@ namespace ts { } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; @@ -1783,7 +1775,7 @@ namespace ts { /** Get the initializer, taking into account defaulted Javascript initializers */ export function getEffectiveInitializer(node: HasExpressionInitializer) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === SyntaxKind.BarBarToken && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -1791,26 +1783,26 @@ namespace ts { return node.initializer; } - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - export function getDeclaredJavascriptInitializer(node: HasExpressionInitializer) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + export function getDeclaredExpandoInitializer(node: HasExpressionInitializer) { const init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - export function getAssignedJavascriptInitializer(node: Node) { + export function getAssignedExpandoInitializer(node: Node) { if (node && node.parent && isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken) { const isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left as EntityNameExpression, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left as EntityNameExpression, node.parent.right, isPrototypeAssignment); } } /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -1819,7 +1811,7 @@ namespace ts { * * This function returns the provided initializer, or undefined if it is not valid. */ - export function getJavascriptInitializer(initializer: Node, isPrototypeAssignment: boolean): Expression | undefined { + export function getExpandoInitializer(initializer: Node, isPrototypeAssignment: boolean): Expression | undefined { if (isCallExpression(initializer)) { const e = skipParentheses(initializer.expression); return e.kind === SyntaxKind.FunctionExpression || e.kind === SyntaxKind.ArrowFunction ? initializer : undefined; @@ -1835,29 +1827,29 @@ namespace ts { } /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name: EntityNameExpression, initializer: Expression, isPrototypeAssignment: boolean) { - const e = isBinaryExpression(initializer) && initializer.operatorToken.kind === SyntaxKind.BarBarToken && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name: EntityNameExpression, initializer: Expression, isPrototypeAssignment: boolean) { + const e = isBinaryExpression(initializer) && initializer.operatorToken.kind === SyntaxKind.BarBarToken && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, (initializer as BinaryExpression).left as EntityNameExpression)) { return e; } } - export function isDefaultedJavascriptInitializer(node: BinaryExpression) { + export function isDefaultedExpandoInitializer(node: BinaryExpression) { const name = isVariableDeclaration(node.parent) ? node.parent.name : isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - export function getOuterNameOfJsInitializer(node: Declaration): DeclarationName | undefined { + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + export function getNameOfExpando(node: Declaration): DeclarationName | undefined { if (isBinaryExpression(node.parent)) { const parent = (node.parent.operatorToken.kind === SyntaxKind.BarBarToken && isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === SyntaxKind.EqualsToken && isIdentifier(parent.left)) { @@ -1913,36 +1905,36 @@ namespace ts { /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - export function getSpecialPropertyAssignmentKind(expr: BinaryExpression): SpecialPropertyAssignmentKind { - const special = getSpecialPropertyAssignmentKindWorker(expr); - return special === SpecialPropertyAssignmentKind.Property || isInJavaScriptFile(expr) ? special : SpecialPropertyAssignmentKind.None; + export function getAssignmentDeclarationKind(expr: BinaryExpression): AssignmentDeclarationKind { + const special = getAssignmentDeclarationKindWorker(expr); + return special === AssignmentDeclarationKind.Property || isInJSFile(expr) ? special : AssignmentDeclarationKind.None; } - function getSpecialPropertyAssignmentKindWorker(expr: BinaryExpression): SpecialPropertyAssignmentKind { + function getAssignmentDeclarationKindWorker(expr: BinaryExpression): AssignmentDeclarationKind { if (expr.operatorToken.kind !== SyntaxKind.EqualsToken || !isPropertyAccessExpression(expr.left)) { - return SpecialPropertyAssignmentKind.None; + return AssignmentDeclarationKind.None; } const lhs = expr.left; if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { // F.prototype = { ... } - return SpecialPropertyAssignmentKind.Prototype; + return AssignmentDeclarationKind.Prototype; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - export function getSpecialPropertyAccessKind(lhs: PropertyAccessExpression): SpecialPropertyAssignmentKind { + export function getAssignmentDeclarationPropertyAccessKind(lhs: PropertyAccessExpression): AssignmentDeclarationKind { if (lhs.expression.kind === SyntaxKind.ThisKeyword) { - return SpecialPropertyAssignmentKind.ThisProperty; + return AssignmentDeclarationKind.ThisProperty; } else if (isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { // module.exports = expr - return SpecialPropertyAssignmentKind.ModuleExports; + return AssignmentDeclarationKind.ModuleExports; } else if (isEntityNameExpression(lhs.expression)) { if (isPrototypeAccess(lhs.expression)) { // F.G....prototype.x = expr - return SpecialPropertyAssignmentKind.PrototypeProperty; + return AssignmentDeclarationKind.PrototypeProperty; } let nextToLast = lhs; @@ -1954,13 +1946,13 @@ namespace ts { if (id.escapedText === "exports" || id.escapedText === "module" && nextToLast.name.escapedText === "exports") { // exports.name = expr OR module.exports.name = expr - return SpecialPropertyAssignmentKind.ExportsProperty; + return AssignmentDeclarationKind.ExportsProperty; } // F.G...x = expr - return SpecialPropertyAssignmentKind.Property; + return AssignmentDeclarationKind.Property; } - return SpecialPropertyAssignmentKind.None; + return AssignmentDeclarationKind.None; } export function getInitializerOfBinaryExpression(expr: BinaryExpression) { @@ -1971,11 +1963,11 @@ namespace ts { } export function isPrototypePropertyAssignment(node: Node): boolean { - return isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === SpecialPropertyAssignmentKind.PrototypeProperty; + return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.PrototypeProperty; } export function isSpecialPropertyDeclaration(expr: PropertyAccessExpression): boolean { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === SyntaxKind.ExpressionStatement && !!getJSDocTypeTag(expr.parent); } @@ -2083,7 +2075,7 @@ namespace ts { function getSourceOfDefaultedAssignment(node: Node): Node | undefined { return isExpressionStatement(node) && isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== SpecialPropertyAssignmentKind.None && + getAssignmentDeclarationKind(node.expression) !== AssignmentDeclarationKind.None && isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === SyntaxKind.BarBarToken ? node.expression.right.right @@ -2403,7 +2395,7 @@ namespace ts { else { const binExp = parent.parent; return isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== SpecialPropertyAssignmentKind.None && + getAssignmentDeclarationKind(binExp) !== AssignmentDeclarationKind.None && (binExp.left.symbol || binExp.symbol) && getNameOfDeclaration(binExp) === name ? binExp @@ -2472,7 +2464,7 @@ namespace ts { node.kind === SyntaxKind.ImportSpecifier || node.kind === SyntaxKind.ExportSpecifier || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) || - isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === SpecialPropertyAssignmentKind.ModuleExports; + isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports; } export function exportAssignmentIsAlias(node: ExportAssignment | BinaryExpression): boolean { @@ -2481,7 +2473,7 @@ namespace ts { } export function getEffectiveBaseTypeNode(node: ClassLikeDeclaration | InterfaceDeclaration) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. const tag = getJSDocAugmentsTag(node); if (tag) { @@ -3253,7 +3245,7 @@ namespace ts { } export interface EmitFileNames { - jsFilePath: string; + jsFilePath: string | undefined; sourceMapFilePath: string | undefined; declarationFilePath: string | undefined; declarationMapPath: string | undefined; @@ -3274,7 +3266,7 @@ namespace ts { const isSourceFileFromExternalLibrary = (file: SourceFile) => host.isSourceFileFromExternalLibrary(file); if (options.outFile || options.out) { const moduleKind = getEmitModuleKind(options); - const moduleEmitEnabled = moduleKind === ModuleKind.AMD || moduleKind === ModuleKind.System; + const moduleEmitEnabled = options.emitDeclarationOnly || moduleKind === ModuleKind.AMD || moduleKind === ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return filter(host.getSourceFiles(), sourceFile => (moduleEmitEnabled || !isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary)); @@ -3287,7 +3279,7 @@ namespace ts { /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ export function sourceFileMayBeEmitted(sourceFile: SourceFile, options: CompilerOptions, isSourceFileFromExternalLibrary: (file: SourceFile) => boolean) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } export function getSourceFilePathInNewDir(fileName: string, host: EmitHost, newDirPath: string): string { @@ -3411,7 +3403,7 @@ namespace ts { */ export function getEffectiveTypeAnnotationNode(node: Node): TypeNode | undefined { const type = (node as HasType).type; - if (type || !isInJavaScriptFile(node)) return type; + if (type || !isInJSFile(node)) return type; return isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : getJSDocType(node); } @@ -3426,7 +3418,7 @@ namespace ts { export function getEffectiveReturnTypeNode(node: SignatureDeclaration | JSDocSignature): TypeNode | undefined { return isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? getJSDocReturnType(node) : undefined); } export function getJSDocTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray { @@ -3743,11 +3735,20 @@ namespace ts { /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ export function tryGetClassExtendingExpressionWithTypeArguments(node: Node): ClassLikeDeclaration | undefined { - if (isExpressionWithTypeArguments(node) && - node.parent.token === SyntaxKind.ExtendsKeyword && - isClassLike(node.parent.parent)) { - return node.parent.parent; - } + const cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; + } + + export interface ClassImplementingOrExtendingExpressionWithTypeArguments { + readonly class: ClassLikeDeclaration; + readonly isImplements: boolean; + } + export function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node: Node): ClassImplementingOrExtendingExpressionWithTypeArguments | undefined { + return isExpressionWithTypeArguments(node) + && isHeritageClause(node.parent) + && isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === SyntaxKind.ImplementsKeyword } + : undefined; } export function isAssignmentExpression(node: Node, excludeCompoundAssignment: true): node is AssignmentExpression; @@ -3774,15 +3775,6 @@ namespace ts { return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } - export function isExpressionWithTypeArgumentsInClassImplementsClause(node: Node): node is ExpressionWithTypeArguments { - return node.kind === SyntaxKind.ExpressionWithTypeArguments - && isEntityNameExpression((node as ExpressionWithTypeArguments).expression) - && node.parent - && (node.parent).token === SyntaxKind.ImplementsKeyword - && node.parent.parent - && isClassLike(node.parent.parent); - } - export function isEntityNameExpression(node: Node): node is EntityNameExpression { return node.kind === SyntaxKind.Identifier || isPropertyAccessEntityNameExpression(node); } @@ -3819,8 +3811,8 @@ namespace ts { } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - export function tryExtractTypeScriptExtension(fileName: string): string | undefined { - return find(supportedTypescriptExtensionsForExtractExtension, extension => fileExtensionIs(fileName, extension)); + export function tryExtractTSExtension(fileName: string): string | undefined { + return find(supportedTSExtensionsForExtractExtension, extension => fileExtensionIs(fileName, extension)); } /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences @@ -3974,6 +3966,27 @@ namespace ts { return getStringFromExpandedCharCodes(expandedCharCodes); } + export function readJson(path: string, host: { readFile(fileName: string): string | undefined }): object { + try { + const jsonText = host.readFile(path); + if (!jsonText) return {}; + const result = parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + + export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean }): boolean { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + const carriageReturnLineFeed = "\r\n"; const lineFeed = "\n"; export function getNewLineCharacter(options: CompilerOptions | PrinterOptions, getNewLine?: () => string): string { @@ -4309,7 +4322,7 @@ namespace ts { /** * clears already present map by calling onDeleteExistingValue callback before deleting that key/value */ - export function clearMap(map: Map, onDeleteValue: (valueInMap: T, key: string) => void) { + export function clearMap(map: { forEach: Map["forEach"]; clear: Map["clear"]; }, onDeleteValue: (valueInMap: T, key: string) => void) { // Remove all map.forEach(onDeleteValue); map.clear(); @@ -4966,11 +4979,11 @@ namespace ts { } case SyntaxKind.BinaryExpression: { const expr = declaration as BinaryExpression; - switch (getSpecialPropertyAssignmentKind(expr)) { - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.PrototypeProperty: + switch (getAssignmentDeclarationKind(expr)) { + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.ThisProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.PrototypeProperty: return (expr.left as PropertyAccessExpression).name; default: return undefined; @@ -5187,7 +5200,7 @@ namespace ts { if (node.typeParameters) { return node.typeParameters; } - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { const decls = getJSDocTypeParameterDeclarations(node); if (decls.length) { return decls; @@ -6593,7 +6606,7 @@ namespace ts { /* @internal */ export function isDeclaration(node: Node): node is NamedDeclaration { if (node.kind === SyntaxKind.TypeParameter) { - return node.parent.kind !== SyntaxKind.JSDocTemplateTag || isInJavaScriptFile(node); + return node.parent.kind !== SyntaxKind.JSDocTemplateTag || isInJSFile(node); } return isDeclarationKind(node.kind); @@ -7065,28 +7078,27 @@ namespace ts { const moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ModuleKind.None && moduleKind < ModuleKind.ES2015 - : moduleKind === ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ModuleKind.System; } export function getEmitDeclarations(compilerOptions: CompilerOptions): boolean { return !!(compilerOptions.declaration || compilerOptions.composite); } - export type StrictOptionName = "noImplicitAny" | "noImplicitThis" | "strictNullChecks" | "strictFunctionTypes" | "strictPropertyInitialization" | "alwaysStrict"; + export type StrictOptionName = "noImplicitAny" | "noImplicitThis" | "strictNullChecks" | "strictFunctionTypes" | "strictBindCallApply" | "strictPropertyInitialization" | "alwaysStrict"; export function getStrictOptionValue(compilerOptions: CompilerOptions, flag: StrictOptionName): boolean { return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } - export function compilerOptionsAffectSemanticDiagnostics(newOptions: CompilerOptions, oldOptions: CompilerOptions) { - if (oldOptions === newOptions) { - return false; - } + export function compilerOptionsAffectSemanticDiagnostics(newOptions: CompilerOptions, oldOptions: CompilerOptions): boolean { + return oldOptions !== newOptions && + semanticDiagnosticsOptionDeclarations.some(option => !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option))); + } - return optionDeclarations.some(option => (!!option.strictFlag && getStrictOptionValue(newOptions, option.name as StrictOptionName) !== getStrictOptionValue(oldOptions, option.name as StrictOptionName)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name])); + export function getCompilerOptionValue(options: CompilerOptions, option: CommandLineOption): unknown { + return option.strictFlag ? getStrictOptionValue(options, option.name as StrictOptionName) : options[option.name]; } export function hasZeroOrOneAsteriskCharacter(str: string): boolean { @@ -7651,6 +7663,15 @@ namespace ts { // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. const reservedCharacterPattern = /[^\w\s\/]/g; + + export function regExpEscape(text: string) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + + function escapeRegExpCharacter(match: string) { + return "\\" + match; + } + const wildcardCharCodes = [CharacterCodes.asterisk, CharacterCodes.question]; export function hasExtension(fileName: string): boolean { @@ -7717,7 +7738,7 @@ namespace ts { return `^(${pattern})${terminator}`; } - function getRegularExpressionsForWildcards(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string[] | undefined { + export function getRegularExpressionsForWildcards(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string[] | undefined { if (specs === undefined || specs.length === 0) { return undefined; } @@ -7981,48 +8002,58 @@ namespace ts { /** * List of supported extensions in order of file resolution precedence. */ - export const supportedTypeScriptExtensions: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts]; + export const supportedTSExtensions: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts]; + export const supportedTSExtensionsWithJson: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts, Extension.Json]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - export const supportedTypescriptExtensionsForExtractExtension: ReadonlyArray = [Extension.Dts, Extension.Ts, Extension.Tsx]; - export const supportedJavascriptExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx]; - export const supportedJavaScriptAndJsonExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx, Extension.Json]; - const allSupportedExtensions: ReadonlyArray = [...supportedTypeScriptExtensions, ...supportedJavascriptExtensions]; + export const supportedTSExtensionsForExtractExtension: ReadonlyArray = [Extension.Dts, Extension.Ts, Extension.Tsx]; + export const supportedJSExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx]; + export const supportedJSAndJsonExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx, Extension.Json]; + const allSupportedExtensions: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions]; + const allSupportedExtensionsWithJson: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions, Extension.Json]; export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray { const needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : supportedTSExtensions; } const extensions = [ - ...needJsExtensions ? allSupportedExtensions : supportedTypeScriptExtensions, - ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined) + ...needJsExtensions ? allSupportedExtensions : supportedTSExtensions, + ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined) ]; return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } - function isJavaScriptLike(scriptKind: ScriptKind | undefined): boolean { + export function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options: CompilerOptions | undefined, supportedExtensions: ReadonlyArray): ReadonlyArray { + if (!options || !options.resolveJsonModule) { return supportedExtensions; } + if (supportedExtensions === allSupportedExtensions) { return allSupportedExtensionsWithJson; } + if (supportedExtensions === supportedTSExtensions) { return supportedTSExtensionsWithJson; } + return [...supportedExtensions, Extension.Json]; + } + + function isJSLike(scriptKind: ScriptKind | undefined): boolean { return scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSX; } - export function hasJavaScriptFileExtension(fileName: string): boolean { - return some(supportedJavascriptExtensions, extension => fileExtensionIs(fileName, extension)); + export function hasJSFileExtension(fileName: string): boolean { + return some(supportedJSExtensions, extension => fileExtensionIs(fileName, extension)); } - export function hasJavaScriptOrJsonFileExtension(fileName: string): boolean { - return supportedJavaScriptAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext)); + export function hasJSOrJsonFileExtension(fileName: string): boolean { + return supportedJSAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext)); } - export function hasTypeScriptFileExtension(fileName: string): boolean { - return some(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension)); + export function hasTSFileExtension(fileName: string): boolean { + return some(supportedTSExtensions, extension => fileExtensionIs(fileName, extension)); } export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: ReadonlyArray) { if (!fileName) { return false; } - for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) { + const supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (const extension of getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions)) { if (fileExtensionIs(fileName, extension)) { return true; } @@ -8152,12 +8183,12 @@ namespace ts { } /** True if an extension is one of the supported TypeScript extensions. */ - export function extensionIsTypeScript(ext: Extension): boolean { + export function extensionIsTS(ext: Extension): boolean { return ext === Extension.Ts || ext === Extension.Tsx || ext === Extension.Dts; } - export function resolutionExtensionIsTypeScriptOrJson(ext: Extension) { - return extensionIsTypeScript(ext) || ext === Extension.Json; + export function resolutionExtensionIsTSOrJson(ext: Extension) { + return extensionIsTS(ext) || ext === Extension.Json; } /** @@ -8345,4 +8376,20 @@ namespace ts { // '/// ' directive. return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } + + export function isJsonEqual(a: unknown, b: unknown): boolean { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && equalOwnProperties(a as MapLike, b as MapLike, isJsonEqual); + } + + export function getOrUpdate(map: Map, key: string, getDefault: () => T): T { + const got = map.get(key); + if (got === undefined) { + const value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } } diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index c091ad5c30c..24ce39fdc4f 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -101,7 +101,7 @@ namespace ts { getGlobalDiagnostics(): ReadonlyArray; getSemanticDiagnostics(): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; - emit(): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult; } export type ReportEmitErrorSummary = (errorCount: number) => void; @@ -109,7 +109,7 @@ namespace ts { /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - export function emitFilesAndReportErrors(program: ProgramToEmitFilesAndReportErrors, reportDiagnostic: DiagnosticReporter, writeFileName?: (s: string) => void, reportSummary?: ReportEmitErrorSummary) { + export function emitFilesAndReportErrors(program: ProgramToEmitFilesAndReportErrors, reportDiagnostic: DiagnosticReporter, writeFileName?: (s: string) => void, reportSummary?: ReportEmitErrorSummary, writeFile?: WriteFileCallback) { // First get and report any syntactic errors. const diagnostics = program.getConfigFileParsingDiagnostics().slice(); const configFileParsingDiagnosticsLength = diagnostics.length; @@ -128,7 +128,7 @@ namespace ts { } // Emit and report any errors we ran into. - const { emittedFiles, emitSkipped, diagnostics: emitDiagnostics } = program.emit(); + const { emittedFiles, emitSkipped, diagnostics: emitDiagnostics } = program.emit(/*targetSourceFile*/ undefined, writeFile); addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { @@ -263,10 +263,11 @@ namespace ts { /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - export function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions { + export function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions { const host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus) as WatchCompilerHostOfFilesAndCompilerOptions; host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } } @@ -274,7 +275,7 @@ namespace ts { namespace ts { export type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - export type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; + export type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; /** Host that has watch functionality used in --watch mode */ export interface WatchHost { /** If provided, called with Diagnostic message that informs about change in watch status */ @@ -360,6 +361,9 @@ namespace ts { /** Compiler options */ options: CompilerOptions; + + /** Project References */ + projectReferences?: ReadonlyArray; } /** @@ -413,11 +417,11 @@ namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - export function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; export function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; - export function createWatchCompilerHost(rootFilesOrConfigFileName: string | string[], options: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions | WatchCompilerHostOfConfigFile { + export function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; + export function createWatchCompilerHost(rootFilesOrConfigFileName: string | string[], options: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions | WatchCompilerHostOfConfigFile { if (isArray(rootFilesOrConfigFileName)) { - return createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options!, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options!, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -463,9 +467,10 @@ namespace ts { const getCurrentDirectory = () => currentDirectory; const readFile: (path: string, encoding?: string) => string | undefined = (path, encoding) => host.readFile(path, encoding); const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, createProgram } = host; - let { rootFiles: rootFileNames, options: compilerOptions } = host; + let { rootFiles: rootFileNames, options: compilerOptions, projectReferences } = host; let configFileSpecs: ConfigFileSpecs; - let configFileParsingDiagnostics: ReadonlyArray | undefined; + let configFileParsingDiagnostics: Diagnostic[] | undefined; + let canConfigFileJsonReportNoInputFiles = false; let hasChangedConfigFileParsingErrors = false; const cachedDirectoryStructureHost = configFileName === undefined ? undefined : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); @@ -542,7 +547,8 @@ namespace ts { }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram, - writeLog + writeLog, + readDirectory: (path, extensions, exclude, include, depth?) => directoryStructureHost.readDirectory!(path, extensions, exclude, include, depth), }; // Cache for the module resolution const resolutionCache = createResolutionCache(compilerHost, configFileName ? @@ -589,9 +595,9 @@ namespace ts { // All resolutions are invalid if user provided resolutions const hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -620,7 +626,7 @@ namespace ts { resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches @@ -824,12 +830,7 @@ namespace ts { function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); const result = getFileNamesFromConfigSpecs(configFileSpecs, getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = filter(configFileParsingDiagnostics, error => !isErrorNoInputFiles(error)); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !some(configFileParsingDiagnostics, isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics!.concat(getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics!, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -861,7 +862,9 @@ namespace ts { rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs!; // TODO: GH#18217 - configFileParsingDiagnostics = getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } diff --git a/src/harness/client.ts b/src/harness/client.ts index ebe97aea070..f59a9ca3188 100644 --- a/src/harness/client.ts +++ b/src/harness/client.ts @@ -3,12 +3,15 @@ namespace ts.server { writeMessage(message: string): void; } - interface RenameEntry extends RenameInfo { - fileName: string; - position: number; - locations: RenameLocation[]; - findInStrings: boolean; - findInComments: boolean; + interface RenameEntry { + readonly renameInfo: RenameInfo; + readonly inputs: { + readonly fileName: string; + readonly position: number; + readonly findInStrings: boolean; + readonly findInComments: boolean; + }; + readonly locations: RenameLocation[]; } /* @internal */ @@ -390,33 +393,41 @@ namespace ts.server { const locations: RenameLocation[] = []; for (const entry of body.locs) { const fileName = entry.file; - for (const loc of entry.locs) { - locations.push({ textSpan: this.decodeSpan(loc, fileName), fileName }); + for (const { start, end, ...prefixSuffixText } of entry.locs) { + locations.push({ textSpan: this.decodeSpan({ start, end }, fileName), fileName, ...prefixSuffixText }); } } - return this.lastRenameEntry = { - canRename: body.info.canRename, - displayName: body.info.displayName, - fullDisplayName: body.info.fullDisplayName, - kind: body.info.kind, - kindModifiers: body.info.kindModifiers, - localizedErrorMessage: body.info.localizedErrorMessage, - triggerSpan: createTextSpanFromBounds(position, position), - fileName, - position, - findInStrings: !!findInStrings, - findInComments: !!findInComments, + const renameInfo = body.info.canRename + ? identity({ + canRename: body.info.canRename, + fileToRename: body.info.fileToRename, + displayName: body.info.displayName, + fullDisplayName: body.info.fullDisplayName, + kind: body.info.kind, + kindModifiers: body.info.kindModifiers, + triggerSpan: createTextSpanFromBounds(position, position), + }) + : identity({ canRename: false, localizedErrorMessage: body.info.localizedErrorMessage }); + this.lastRenameEntry = { + renameInfo, + inputs: { + fileName, + position, + findInStrings: !!findInStrings, + findInComments: !!findInComments, + }, locations, }; + return renameInfo; } findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] { if (!this.lastRenameEntry || - this.lastRenameEntry.fileName !== fileName || - this.lastRenameEntry.position !== position || - this.lastRenameEntry.findInStrings !== findInStrings || - this.lastRenameEntry.findInComments !== findInComments) { + this.lastRenameEntry.inputs.fileName !== fileName || + this.lastRenameEntry.inputs.position !== position || + this.lastRenameEntry.inputs.findInStrings !== findInStrings || + this.lastRenameEntry.inputs.findInComments !== findInComments) { this.getRenameInfo(fileName, position, findInStrings, findInComments); } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 214e1f295ab..dc28871d1c0 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -420,12 +420,12 @@ namespace FourSlash { } } - public goToEachRange(action: () => void) { + public goToEachRange(action: (range: Range) => void) { const ranges = this.getRanges(); assert(ranges.length); for (const range of ranges) { this.selectRange(range); - action(); + action(range); } } @@ -593,7 +593,7 @@ namespace FourSlash { public verifyNoErrors() { ts.forEachKey(this.inputFiles, fileName => { if (!ts.isAnySupportedFileExtension(fileName) - || !this.getProgram().getCompilerOptions().allowJs && !ts.extensionIsTypeScript(ts.extensionFromPath(fileName))) return; + || !this.getProgram().getCompilerOptions().allowJs && !ts.extensionIsTS(ts.extensionFromPath(fileName))) return; const errors = this.getDiagnostics(fileName).filter(e => e.category !== ts.DiagnosticCategory.Suggestion); if (errors.length) { this.printErrorLog(/*expectErrors*/ false, errors); @@ -908,8 +908,8 @@ namespace FourSlash { } private verifyCompletionEntry(actual: ts.CompletionEntry, expected: FourSlashInterface.ExpectedCompletionEntry) { - const { insertText, replacementSpan, hasAction, isRecommended, kind, text, documentation, source, sourceDisplay } = typeof expected === "string" - ? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, text: undefined, documentation: undefined, source: undefined, sourceDisplay: undefined } + const { insertText, replacementSpan, hasAction, isRecommended, kind, text, documentation, tags, source, sourceDisplay } = typeof expected === "string" + ? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, text: undefined, documentation: undefined, tags: undefined, source: undefined, sourceDisplay: undefined } : expected; if (actual.insertText !== insertText) { @@ -929,7 +929,7 @@ namespace FourSlash { assert.equal(actual.isRecommended, isRecommended); assert.equal(actual.source, source); - if (text) { + if (text !== undefined) { const actualDetails = this.getCompletionEntryDetails(actual.name, actual.source)!; assert.equal(ts.displayPartsToString(actualDetails.displayParts), text); assert.equal(ts.displayPartsToString(actualDetails.documentation), documentation || ""); @@ -937,9 +937,10 @@ namespace FourSlash { // assert.equal(actualDetails.kind, actual.kind); assert.equal(actualDetails.kindModifiers, actual.kindModifiers); assert.equal(actualDetails.source && ts.displayPartsToString(actualDetails.source), sourceDisplay); + assert.deepEqual(actualDetails.tags, tags); } else { - assert(documentation === undefined && sourceDisplay === undefined, "If specifying completion details, should specify 'text'"); + assert(documentation === undefined && tags === undefined && sourceDisplay === undefined, "If specifying completion details, should specify 'text'"); } } @@ -1363,7 +1364,7 @@ Actual: ${stringify(fullActual)}`); public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: TextSpan, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], - tags: ts.JSDocTagInfo[] + tags: ts.JSDocTagInfo[] | undefined ) { const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; @@ -1372,11 +1373,16 @@ Actual: ${stringify(fullActual)}`); assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan")); assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.displayParts), TestState.getDisplayPartsJson(displayParts), this.messageAtLastKnownMarker("QuickInfo displayParts")); assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.documentation), TestState.getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation")); - assert.equal(actualQuickInfo.tags!.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags")); - ts.zipWith(tags, actualQuickInfo.tags!, (expectedTag, actualTag) => { - assert.equal(expectedTag.name, actualTag.name); - assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name)); - }); + if (!actualQuickInfo.tags || !tags) { + assert.equal(actualQuickInfo.tags, tags, this.messageAtLastKnownMarker("QuickInfo tags")); + } + else { + assert.equal(actualQuickInfo.tags.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags")); + ts.zipWith(tags, actualQuickInfo.tags, (expectedTag, actualTag) => { + assert.equal(expectedTag.name, actualTag.name); + assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name)); + }); + } } public verifyRangesAreRenameLocations(options?: Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges?: Range[] }) { @@ -1389,7 +1395,7 @@ Actual: ${stringify(fullActual)}`); } } - public verifyRenameLocations(startRanges: ArrayOrSingle, options: ReadonlyArray | { findInStrings?: boolean, findInComments?: boolean, ranges: ReadonlyArray }) { + public verifyRenameLocations(startRanges: ArrayOrSingle, options: FourSlashInterface.RenameLocationsOptions) { const { findInStrings = false, findInComments = false, ranges = this.getRanges() } = ts.isArray(options) ? { findInStrings: false, findInComments: false, ranges: options } : options; for (const startRange of toArray(startRanges)) { @@ -1406,7 +1412,10 @@ Actual: ${stringify(fullActual)}`); const sort = (locations: ReadonlyArray | undefined) => locations && ts.sort(locations, (r1, r2) => ts.compareStringsCaseSensitive(r1.fileName, r2.fileName) || r1.textSpan.start - r2.textSpan.start); - assert.deepEqual(sort(references), sort(ranges.map((r): ts.RenameLocation => ({ fileName: r.fileName, textSpan: ts.createTextSpanFromRange(r) })))); + assert.deepEqual(sort(references), sort(ranges.map((rangeOrOptions): ts.RenameLocation => { + const { range, ...prefixSuffixText } = "range" in rangeOrOptions ? rangeOrOptions : { range: rangeOrOptions }; + return { fileName: range.fileName, textSpan: ts.createTextSpanFromRange(range), ...prefixSuffixText }; + }))); } } @@ -1525,22 +1534,25 @@ Actual: ${stringify(fullActual)}`); } } - public verifyRenameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string) { + public verifyRenameInfoSucceeded(displayName: string | undefined, fullDisplayName: string | undefined, kind: string | undefined, kindModifiers: string | undefined, fileToRename: string | undefined, expectedRange: Range | undefined): void { const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (!renameInfo.canRename) { - this.raiseError("Rename did not succeed"); + throw this.raiseError("Rename did not succeed"); } this.validate("displayName", displayName, renameInfo.displayName); this.validate("fullDisplayName", fullDisplayName, renameInfo.fullDisplayName); this.validate("kind", kind, renameInfo.kind); this.validate("kindModifiers", kindModifiers, renameInfo.kindModifiers); + this.validate("fileToRename", fileToRename, renameInfo.fileToRename); - if (this.getRanges().length !== 1) { - this.raiseError("Expected a single range to be selected in the test file."); + if (!expectedRange) { + if (this.getRanges().length !== 1) { + this.raiseError("Expected a single range to be selected in the test file."); + } + expectedRange = this.getRanges()[0]; } - const expectedRange = this.getRanges()[0]; if (renameInfo.triggerSpan.start !== expectedRange.pos || ts.textSpanEnd(renameInfo.triggerSpan) !== expectedRange.end) { this.raiseError("Expected triggerSpan [" + expectedRange.pos + "," + expectedRange.end + "). Got [" + @@ -1551,9 +1563,8 @@ Actual: ${stringify(fullActual)}`); public verifyRenameInfoFailed(message?: string) { const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (renameInfo.canRename) { - this.raiseError("Rename was expected to fail"); + throw this.raiseError("Rename was expected to fail"); } - this.validate("error", message, renameInfo.localizedErrorMessage); } @@ -2493,9 +2504,7 @@ Actual: ${stringify(fullActual)}`); const { changes, commands } = this.languageService.getCombinedCodeFix({ type: "file", fileName: this.activeFile.fileName }, fixId, this.formatCodeSettings, ts.emptyOptions); assert.deepEqual | undefined>(commands, expectedCommands); - assert(changes.every(c => c.fileName === this.activeFile.fileName), "TODO: support testing codefixes that touch multiple files"); - this.applyChanges(changes); - this.verifyCurrentFileContent(newFileContent); + this.verifyNewContent({ newFileContent }, changes); } /** @@ -2507,10 +2516,10 @@ Actual: ${stringify(fullActual)}`); * @param expectedContents The contents of the file after the fixes are applied. * @param fileName The file to check. If not supplied, the current open file is used. */ - public verifyFileAfterCodeFix(expectedContents: string, fileName?: string) { + public verifyFileAfterCodeFix(expectedContents: string, fileName?: string, index?: number) { fileName = fileName ? fileName : this.activeFile.fileName; - this.applyCodeActions(this.getCodeFixes(fileName)); + this.applyCodeActions(this.getCodeFixes(fileName), index); const actualContents: string = this.getFileContent(fileName); if (this.removeWhitespace(actualContents) !== this.removeWhitespace(expectedContents)) { @@ -3380,6 +3389,19 @@ Actual: ${stringify(fullActual)}`); private getApplicableRefactorsWorker(positionOrRange: number | ts.TextRange, fileName: string, preferences = ts.emptyOptions): ReadonlyArray { return this.languageService.getApplicableRefactors(fileName, positionOrRange, preferences) || ts.emptyArray; } + + public generateTypes(examples: ReadonlyArray): void { + for (const { name = "example", value, output, outputBaseline } of examples) { + const actual = ts.generateTypesForModule(name, value, this.formatCodeSettings); + if (outputBaseline) { + if (actual === undefined) throw ts.Debug.fail(); + Harness.Baseline.runBaseline(ts.combinePaths("generateTypes", outputBaseline + ts.Extension.Dts), actual); + } + else { + assert.equal(actual, output, `generateTypes output for ${name} does not match`); + } + } + } } function updateTextRangeForTextChanges({ pos, end }: ts.TextRange, textChanges: ReadonlyArray): ts.TextRange { @@ -3433,7 +3455,7 @@ Actual: ${stringify(fullActual)}`); // Parse out the files and their metadata const testData = parseTestData(absoluteBasePath, content, absoluteFileName); const state = new TestState(absoluteBasePath, testType, testData); - const output = ts.transpileModule(content, { reportDiagnostics: true }); + const output = ts.transpileModule(content, { reportDiagnostics: true, compilerOptions: { target: ts.ScriptTarget.ES2015 } }); if (output.diagnostics!.length > 0) { throw new Error(`Syntax error in ${absoluteBasePath}: ${output.diagnostics![0].messageText}`); } @@ -3977,7 +3999,7 @@ namespace FourSlashInterface { this.state.goToRangeStart(range); } - public eachRange(action: () => void) { + public eachRange(action: (range: FourSlash.Range) => void) { this.state.goToEachRange(action); } @@ -4366,6 +4388,10 @@ namespace FourSlashInterface { this.state.verifyRangeAfterCodeFix(expectedText, includeWhiteSpace, errorCode, index); } + public fileAfterCodeFix(expectedContents: string, fileName?: string, index?: number) { + this.state.verifyFileAfterCodeFix(expectedContents, fileName, index); + } + public codeFixAll(options: VerifyCodeFixAllOptions): void { this.state.verifyCodeFixAll(options); } @@ -4456,15 +4482,15 @@ namespace FourSlashInterface { this.state.verifySemanticClassifications(classifications); } - public renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string) { - this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers); + public renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string, fileToRename?: string, expectedRange?: FourSlash.Range) { + this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers, fileToRename, expectedRange); } public renameInfoFailed(message?: string) { this.state.verifyRenameInfoFailed(message); } - public renameLocations(startRanges: ArrayOrSingle, options: FourSlash.Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges: FourSlash.Range[] }) { + public renameLocations(startRanges: ArrayOrSingle, options: RenameLocationsOptions) { this.state.verifyRenameLocations(startRanges, options); } @@ -4503,6 +4529,18 @@ namespace FourSlashInterface { public noMoveToNewFile(): void { this.state.noMoveToNewFile(); } + + public generateTypes(...options: GenerateTypesOptions[]): void { + this.state.generateTypes(options); + } + } + + export interface GenerateTypesOptions { + readonly name?: string; + readonly value: unknown; + // Exactly one of these should be set: + readonly output?: string; + readonly outputBaseline?: string; } export class Edit { @@ -4799,6 +4837,7 @@ namespace FourSlashInterface { readonly text: string; readonly documentation: string; readonly sourceDisplay?: string; + readonly tags?: ReadonlyArray; }; export interface CompletionsAtOptions extends Partial { triggerCharacter?: ts.CompletionsTriggerCharacter; @@ -4891,7 +4930,7 @@ namespace FourSlashInterface { export interface VerifyCodeFixAllOptions { fixId: string; fixAllDescription: string; - newFileContent: string; + newFileContent: NewFileContent; commands: ReadonlyArray<{}>; } @@ -4926,4 +4965,11 @@ namespace FourSlashInterface { readonly newFileContents: { readonly [fileName: string]: string }; readonly preferences?: ts.UserPreferences; } + + export type RenameLocationsOptions = ReadonlyArray | { + readonly findInStrings?: boolean; + readonly findInComments?: boolean; + readonly ranges: ReadonlyArray; + }; + export type RenameLocationOptions = FourSlash.Range | { readonly range: FourSlash.Range, readonly prefixText?: string, readonly suffixText?: string }; } diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 23ee10d7412..5896ff3a782 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -1159,7 +1159,7 @@ namespace Harness { } // If not a primitive, the possible types are specified in what is effectively a map of options. case "list": - return ts.parseListTypeOption(option, value, errors); + return ts.parseListTypeOption(option, value, errors); default: return ts.parseCustomTypeOption(option, value, errors); } diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index fa9c88d3ffa..e90f29446c3 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -268,7 +268,7 @@ namespace Harness.LanguageService { getHost(): LanguageServiceAdapterHost { return this.host; } getLanguageService(): ts.LanguageService { return ts.createLanguageService(this.host); } getClassifier(): ts.Classifier { return ts.createClassifier(); } - getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJavaScriptFileExtension(fileName)); } + getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJSFileExtension(fileName)); } } /// Shim adapter diff --git a/src/harness/utils.ts b/src/harness/utils.ts index 4650badadaf..5938db7d62c 100644 --- a/src/harness/utils.ts +++ b/src/harness/utils.ts @@ -7,6 +7,21 @@ namespace utils { return text !== undefined ? text.replace(testPathPrefixRegExp, (_, scheme) => scheme || (retainTrailingDirectorySeparator ? "/" : "")) : undefined!; // TODO: GH#18217 } + function createDiagnosticMessageReplacer string[]>(diagnosticMessage: ts.DiagnosticMessage, replacer: R) { + const messageParts = diagnosticMessage.message.split(/{\d+}/g); + const regExp = new RegExp(`^(?:${messageParts.map(ts.regExpEscape).join("(.*?)")})$`); + type Args = R extends (messageArgs: string[], ...args: infer A) => string[] ? A : []; + return (text: string, ...args: Args) => text.replace(regExp, (_, ...fixedArgs) => ts.formatStringFromArgs(diagnosticMessage.message, replacer(fixedArgs, ...args))); + } + + const replaceTypesVersionsMessage = createDiagnosticMessageReplacer( + ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, + ([entry, , moduleName], compilerVersion) => [entry, compilerVersion, moduleName]); + + export function sanitizeTraceResolutionLogEntry(text: string) { + return text && removeTestPathPrefixes(replaceTypesVersionsMessage(text, "3.1.0-dev")); + } + /** * Removes leading indentation from a template literal string. */ @@ -82,4 +97,16 @@ namespace utils { export function addUTF8ByteOrderMark(text: string) { return getByteOrderMarkLength(text) === 0 ? "\u00EF\u00BB\u00BF" + text : text; } + + export function theory(name: string, cb: (...args: T) => void, data: T[]) { + for (const entry of data) { + it(`${name}(${entry.map(formatTheoryDatum).join(", ")})`, () => cb(...entry)); + } + } + + function formatTheoryDatum(value: any) { + return typeof value === "function" ? value.name || "" : + value === undefined ? "undefined" : + JSON.stringify(value); + } } \ No newline at end of file diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 57fa33a84c2..d2b7c7869c5 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -4,6 +4,8 @@ namespace ts.TestFSWithWatch { content: `/// interface Boolean {} interface Function {} +interface CallableFunction {} +interface NewableFunction {} interface IArguments {} interface Number { toExponential: any; } interface Object {} @@ -187,9 +189,10 @@ interface Array {}` } export function checkArray(caption: string, actual: ReadonlyArray, expected: ReadonlyArray) { + checkMapKeys(caption, arrayToMap(actual, identity), expected); assert.equal(actual.length, expected.length, `${caption}: incorrect actual number of files, expected:\r\n${expected.join("\r\n")}\r\ngot: ${actual.join("\r\n")}`); for (const f of expected) { - assert.equal(true, contains(actual, f), `${caption}: expected to find ${f} in ${actual}`); + assert.isTrue(contains(actual, f), `${caption}: expected to find ${f} in ${actual}`); } } @@ -654,7 +657,7 @@ interface Array {}` invokeWatcherCallbacks(this.watchedDirectoriesRecursive.get(this.toPath(folderFullPath))!, cb => this.directoryCallback(cb, relativePath)); } - invokeFileWatcher(fileFullPath: string, eventKind: FileWatcherEventKind, useFileNameInCallback?: boolean) { + private invokeFileWatcher(fileFullPath: string, eventKind: FileWatcherEventKind, useFileNameInCallback?: boolean) { invokeWatcherCallbacks(this.watchedFiles.get(this.toPath(fileFullPath))!, ({ cb, fileName }) => cb(useFileNameInCallback ? fileName : fileFullPath, eventKind)); } @@ -934,7 +937,12 @@ interface Array {}` const folder = this.fs.get(base) as FsFolder; Debug.assert(isFsFolder(folder)); - this.addFileOrFolderInFolder(folder, file); + if (!this.fs.has(file.path)) { + this.addFileOrFolderInFolder(folder, file); + } + else { + this.modifyFile(path, content); + } } write(message: string) { diff --git a/src/harness/vpath.ts b/src/harness/vpath.ts index 6211fc9278a..68ba0465e50 100644 --- a/src/harness/vpath.ts +++ b/src/harness/vpath.ts @@ -21,8 +21,8 @@ namespace vpath { export import relative = ts.getRelativePathFromDirectory; export import beneath = ts.containsPath; export import changeExtension = ts.changeAnyExtension; - export import isTypeScript = ts.hasTypeScriptFileExtension; - export import isJavaScript = ts.hasJavaScriptFileExtension; + export import isTypeScript = ts.hasTSFileExtension; + export import isJavaScript = ts.hasJSFileExtension; const invalidRootComponentRegExp = /^(?!(\/|\/\/\w+\/|[a-zA-Z]:\/?|)$)/; const invalidNavigableComponentRegExp = /[:*?"<>|]/; @@ -133,4 +133,4 @@ namespace vpath { export function isTsConfigFile(path: string): boolean { return path.indexOf("tsconfig") !== -1 && path.indexOf("json") !== -1; } -} \ No newline at end of file +} diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index e9c96ba2bf6..ad21068d578 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -21,13 +21,13 @@ namespace ts.JsTyping { export interface CachedTyping { typingLocation: string; - version: Semver; + version: Version; } /* @internal */ export function isTypingUpToDate(cachedTyping: CachedTyping, availableTypingVersions: MapLike) { - const availableVersion = Semver.parse(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")!); - return !availableVersion.greaterThan(cachedTyping.version); + const availableVersion = new Version(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")!); + return availableVersion.compareTo(cachedTyping.version) <= 0; } /* @internal */ @@ -122,7 +122,7 @@ namespace ts.JsTyping { // Only infer typings for .js and .jsx files fileNames = mapDefined(fileNames, fileName => { const path = normalizePath(fileName); - if (hasJavaScriptFileExtension(path)) { + if (hasJSFileExtension(path)) { return path; } }); @@ -218,7 +218,7 @@ namespace ts.JsTyping { */ function getTypingNamesFromSourceFileNames(fileNames: string[]) { const fromFileNames = mapDefined(fileNames, j => { - if (!hasJavaScriptFileExtension(j)) return undefined; + if (!hasJSFileExtension(j)) return undefined; const inferredTypingName = removeFileExtension(getBaseFileName(j.toLowerCase())); const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); diff --git a/src/jsTyping/semver.ts b/src/jsTyping/semver.ts deleted file mode 100644 index 1c58da8c8f7..00000000000 --- a/src/jsTyping/semver.ts +++ /dev/null @@ -1,61 +0,0 @@ -/* @internal */ -namespace ts { - function stringToInt(str: string): number { - const n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error(`Error in parseInt(${JSON.stringify(str)})`); - } - return n; - } - - const isPrereleaseRegex = /^(.*)-next.\d+/; - const prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - const semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - - export class Semver { - static parse(semver: string): Semver { - const isPrerelease = isPrereleaseRegex.test(semver); - const result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error(`Unexpected semver: ${semver} (isPrerelease: ${isPrerelease})`); - } - return result; - } - - static fromRaw({ major, minor, patch, isPrerelease }: Semver): Semver { - return new Semver(major, minor, patch, isPrerelease); - } - - // This must parse the output of `versionString`. - private static tryParse(semver: string, isPrerelease: boolean): Semver | undefined { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - const rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - const match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - } - - private constructor( - readonly major: number, readonly minor: number, readonly patch: number, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - readonly isPrerelease: boolean) { } - - get versionString(): string { - return this.isPrerelease ? `${this.major}.${this.minor}.0-next.${this.patch}` : `${this.major}.${this.minor}.${this.patch}`; - } - - equals(sem: Semver): boolean { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - } - - greaterThan(sem: Semver): boolean { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - } - } -} \ No newline at end of file diff --git a/src/jsTyping/shared.ts b/src/jsTyping/shared.ts index 54b34193d06..78e9fe051b7 100644 --- a/src/jsTyping/shared.ts +++ b/src/jsTyping/shared.ts @@ -4,6 +4,7 @@ namespace ts.server { export const ActionSet: ActionSet = "action::set"; export const ActionInvalidate: ActionInvalidate = "action::invalidate"; export const ActionPackageInstalled: ActionPackageInstalled = "action::packageInstalled"; + export const ActionValueInspected: ActionValueInspected = "action::valueInspected"; export const EventTypesRegistry: EventTypesRegistry = "event::typesRegistry"; export const EventBeginInstallTypes: EventBeginInstallTypes = "event::beginInstallTypes"; export const EventEndInstallTypes: EventEndInstallTypes = "event::endInstallTypes"; diff --git a/src/jsTyping/tsconfig.json b/src/jsTyping/tsconfig.json index 4886463e163..ac5b8b19c29 100644 --- a/src/jsTyping/tsconfig.json +++ b/src/jsTyping/tsconfig.json @@ -16,7 +16,6 @@ "files": [ "shared.ts", "types.ts", - "jsTyping.ts", - "semver.ts" + "jsTyping.ts" ] } diff --git a/src/jsTyping/types.ts b/src/jsTyping/types.ts index 4e00c2eb6f5..408d30a6511 100644 --- a/src/jsTyping/types.ts +++ b/src/jsTyping/types.ts @@ -2,6 +2,7 @@ declare namespace ts.server { export type ActionSet = "action::set"; export type ActionInvalidate = "action::invalidate"; export type ActionPackageInstalled = "action::packageInstalled"; + export type ActionValueInspected = "action::valueInspected"; export type EventTypesRegistry = "event::typesRegistry"; export type EventBeginInstallTypes = "event::beginInstallTypes"; export type EventEndInstallTypes = "event::endInstallTypes"; @@ -12,7 +13,7 @@ declare namespace ts.server { } export interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } export interface TypingInstallerRequestWithProjectName { @@ -20,7 +21,7 @@ declare namespace ts.server { } /* @internal */ - export type TypingInstallerRequestUnion = DiscoverTypings | CloseProject | TypesRegistryRequest | InstallPackageRequest; + export type TypingInstallerRequestUnion = DiscoverTypings | CloseProject | TypesRegistryRequest | InstallPackageRequest | InspectValueRequest; export interface DiscoverTypings extends TypingInstallerRequestWithProjectName { readonly fileNames: string[]; @@ -47,6 +48,12 @@ declare namespace ts.server { readonly projectRootPath: Path; } + /* @internal */ + export interface InspectValueRequest { + readonly kind: "inspectValue"; + readonly options: InspectValueOptions; + } + /* @internal */ export interface TypesRegistryResponse extends TypingInstallerResponse { readonly kind: EventTypesRegistry; @@ -59,6 +66,12 @@ declare namespace ts.server { readonly message: string; } + /* @internal */ + export interface InspectValueResponse { + readonly kind: ActionValueInspected; + readonly result: ValueInfo; + } + export interface InitializationFailedResponse extends TypingInstallerResponse { readonly kind: EventInitializationFailed; readonly message: string; @@ -106,5 +119,5 @@ declare namespace ts.server { } /* @internal */ - export type TypingInstallerResponseUnion = SetTypings | InvalidateCachedTypings | TypesRegistryResponse | PackageInstalledResponse | InstallTypes | InitializationFailedResponse; + export type TypingInstallerResponseUnion = SetTypings | InvalidateCachedTypings | TypesRegistryResponse | PackageInstalledResponse | InspectValueResponse | InstallTypes | InitializationFailedResponse; } diff --git a/src/lib/es2015.promise.d.ts b/src/lib/es2015.promise.d.ts index 14602c0b5ed..2a98f215193 100644 --- a/src/lib/es2015.promise.d.ts +++ b/src/lib/es2015.promise.d.ts @@ -7,7 +7,7 @@ interface PromiseConstructor { /** * Creates a new Promise. * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, + * a resolve callback used to resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; @@ -193,4 +193,4 @@ interface PromiseConstructor { resolve(): Promise; } -declare var Promise: PromiseConstructor; \ No newline at end of file +declare var Promise: PromiseConstructor; diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 015eec5c3e0..c8e99f0d1db 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -295,6 +295,66 @@ interface FunctionConstructor { declare const Function: FunctionConstructor; +interface CallableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: (this: T) => R, thisArg: T): R; + apply(this: (this: T, ...args: A) => R, thisArg: T, args: A): R; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: (this: T, ...args: A) => R, thisArg: T): (...args: A) => R; + bind(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R; + bind(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R; +} + +interface NewableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: new () => T, thisArg: T): void; + apply(this: new (...args: A) => T, thisArg: T, args: A): void; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: new (...args: A) => T, thisArg: T, ...args: A): void; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: new (...args: A) => R, thisArg: any): new (...args: A) => R; + bind(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2, arg3: A3): new (...args: A) => R; + bind(this: new (...args: AX[]) => R, thisArg: any, ...args: AX[]): new (...args: AX[]) => R; +} + interface IArguments { [index: number]: any; length: number; @@ -1350,7 +1410,7 @@ type Readonly = { }; /** - * From T pick a set of properties K + * From T, pick a set of properties whose keys are in the union K */ type Pick = { [P in K]: T[P]; diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index f46e461c240..1760da2a463 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,10151 +1,10151 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - or -. For example '{0}' or '{1}'.]]> - - o -. Por ejemplo, '{0}' o '{1}'.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - type.]]> - - global.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ()' instead.]]> - - ()" en su lugar.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + or -. For example '{0}' or '{1}'.]]> + + o -. Por ejemplo, '{0}' o '{1}'.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type.]]> + + global.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ()' instead.]]> + + ()" en su lugar.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index ddbfd8ac389..30a9844eaf8 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -5,6 +5,8 @@ namespace ts.server { // tslint:disable variable-name export const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + export const ProjectLoadingStartEvent = "projectLoadingStart"; + export const ProjectLoadingFinishEvent = "projectLoadingFinish"; export const SurveyReady = "surveyReady"; export const LargeFileReferencedEvent = "largeFileReferenced"; export const ConfigFileDiagEvent = "configFileDiag"; @@ -18,6 +20,16 @@ namespace ts.server { data: { openFiles: string[]; }; } + export interface ProjectLoadingStartEvent { + eventName: typeof ProjectLoadingStartEvent; + data: { project: Project; reason: string; }; + } + + export interface ProjectLoadingFinishEvent { + eventName: typeof ProjectLoadingFinishEvent; + data: { project: Project; }; + } + export interface SurveyReady { eventName: typeof SurveyReady; data: { surveyId: string; }; @@ -44,6 +56,24 @@ namespace ts.server { readonly data: ProjectInfoTelemetryEventData; } +/* __GDPR__ + "projectInfo" : { + "${include}": ["${TypeScriptCommonProperties}"], + "projectId": { "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight", "endpoint": "ProjectId" }, + "fileStats": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "compilerOptions": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "extends": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "files": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "include": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "exclude": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "compileOnSave": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "typeAcquisition": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "configFileName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "projectType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "languageServiceEnabled": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "version": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } + } + */ export interface ProjectInfoTelemetryEventData { /** Cryptographically secure hash of project file location. */ readonly projectId: string; @@ -104,7 +134,15 @@ namespace ts.server { readonly checkJs: boolean; } - export type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + export type ProjectServiceEvent = LargeFileReferencedEvent | + SurveyReady | + ProjectsUpdatedInBackgroundEvent | + ProjectLoadingStartEvent | + ProjectLoadingFinishEvent | + ConfigFileDiagEvent | + ProjectLanguageServiceStateEvent | + ProjectInfoTelemetryEvent | + OpenFileInfoTelemetryEvent; export type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; @@ -291,7 +329,8 @@ namespace ts.server { ClosedScriptInfo = "Closed Script info", ConfigFileForInferredRoot = "Config file for the inferred project root", FailedLookupLocation = "Directory of Failed lookup locations in module resolution", - TypeRoots = "Type root directory" + TypeRoots = "Type root directory", + NodeModulesForClosedScriptInfo = "node_modules for closed script infos in them", } const enum ConfigFileWatcherStatus { @@ -353,10 +392,18 @@ namespace ts.server { return !!(infoOrFileName as ScriptInfo).containingProjects; } + interface ScriptInfoInNodeModulesWatcher extends FileWatcher { + refCount: number; + } + function getDetailWatchInfo(watchType: WatchType, project: Project | undefined) { return `Project: ${project ? project.getProjectName() : ""} WatchType: ${watchType}`; } + function isScriptInfoWatchedFromNodeModules(info: ScriptInfo) { + return !info.isScriptOpen() && info.mTime !== undefined; + } + /*@internal*/ export function updateProjectIfDirty(project: Project) { return project.dirty && project.updateGraph(); @@ -380,6 +427,7 @@ namespace ts.server { * Container of all known scripts */ private readonly filenameToScriptInfo = createMap(); + private readonly scriptInfoInNodeModulesWatchers = createMap (); /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -438,7 +486,7 @@ namespace ts.server { private readonly hostConfiguration: HostConfiguration; private safelist: SafeList = defaultTypeSafeList; - private legacySafelist: { [key: string]: string } = {}; + private readonly legacySafelist = createMap(); private pendingProjectUpdates = createMap(); /* @internal */ @@ -590,14 +638,14 @@ namespace ts.server { this.safelist = raw.typesMap; for (const key in raw.simpleMap) { if (raw.simpleMap.hasOwnProperty(key)) { - this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); } } } catch (e) { this.logger.info(`Error loading types map: ${e}`); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist.clear(); } } @@ -693,6 +741,33 @@ namespace ts.server { this.eventHandler(event); } + /* @internal */ + sendProjectLoadingStartEvent(project: ConfiguredProject, reason: string) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + const event: ProjectLoadingStartEvent = { + eventName: ProjectLoadingStartEvent, + data: { project, reason } + }; + this.eventHandler(event); + } + + /* @internal */ + sendProjectLoadingFinishEvent(project: ConfiguredProject) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + + project.sendLoadingProjectFinish = false; + const event: ProjectLoadingFinishEvent = { + eventName: ProjectLoadingFinishEvent, + data: { project } + }; + this.eventHandler(event); + } + /* @internal */ delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project: Project) { this.delayUpdateProjectGraph(project); @@ -927,6 +1002,7 @@ namespace ts.server { else { this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.ReloadingInferredRootFiles); project.pendingReload = ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = "Change in config file detected"; this.delayUpdateProjectGraph(project); // As we scheduled the update on configured project graph, // we would need to schedule the project reload for only the root of inferred projects @@ -1447,14 +1523,14 @@ namespace ts.server { for (const f of fileNames) { const fileName = propertyReader.getFileName(f); - if (hasTypeScriptFileExtension(fileName)) { + if (hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader, hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader, hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // Keep the size as zero since it's disabled return fileName; } @@ -1464,14 +1540,14 @@ namespace ts.server { return; - function getExceedLimitMessage(context: { propertyReader: FilePropertyReader, hasTypeScriptFileExtension: (filename: string) => boolean, host: ServerHost }, totalNonTsFileSize: number) { + function getExceedLimitMessage(context: { propertyReader: FilePropertyReader, hasTSFileExtension: (filename: string) => boolean, host: ServerHost }, totalNonTsFileSize: number) { const files = getTop5LargestFiles(context); return `Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${files.map(file => `${file.name}:${file.size}`).join(", ")}`; } - function getTop5LargestFiles({ propertyReader, hasTypeScriptFileExtension, host }: { propertyReader: FilePropertyReader, hasTypeScriptFileExtension: (filename: string) => boolean, host: ServerHost }) { + function getTop5LargestFiles({ propertyReader, hasTSFileExtension, host }: { propertyReader: FilePropertyReader, hasTSFileExtension: (filename: string) => boolean, host: ServerHost }) { return fileNames.map(f => propertyReader.getFileName(f)) - .filter(name => hasTypeScriptFileExtension(name)) + .filter(name => hasTSFileExtension(name)) .map(name => ({ name, size: host.getFileSize!(name) })) // TODO: GH#18217 .sort((a, b) => b.size - a.size) .slice(0, 5); @@ -1585,22 +1661,23 @@ namespace ts.server { } /* @internal */ - private createConfiguredProjectWithDelayLoad(configFileName: NormalizedPath) { + private createConfiguredProjectWithDelayLoad(configFileName: NormalizedPath, reason: string) { const project = this.createConfiguredProject(configFileName); project.pendingReload = ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; return project; } /* @internal */ - private createAndLoadConfiguredProject(configFileName: NormalizedPath) { + private createAndLoadConfiguredProject(configFileName: NormalizedPath, reason: string) { const project = this.createConfiguredProject(configFileName); - this.loadConfiguredProject(project); + this.loadConfiguredProject(project, reason); return project; } /* @internal */ - private createLoadAndUpdateConfiguredProject(configFileName: NormalizedPath) { - const project = this.createAndLoadConfiguredProject(configFileName); + private createLoadAndUpdateConfiguredProject(configFileName: NormalizedPath, reason: string) { + const project = this.createAndLoadConfiguredProject(configFileName, reason); project.updateGraph(); return project; } @@ -1609,7 +1686,9 @@ namespace ts.server { * Read the config file of the project, and update the project root file names. */ /* @internal */ - private loadConfiguredProject(project: ConfiguredProject) { + private loadConfiguredProject(project: ConfiguredProject, reason: string) { + this.sendProjectLoadingStartEvent(project, reason); + // Read updated contents from disk const configFilename = normalizePath(project.getConfigFilePath()); @@ -1646,6 +1725,7 @@ namespace ts.server { }; } project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.canConfigFileJsonReportNoInputFiles = canJsonReportNoInutFiles(parsedCommandLine.raw); project.setProjectErrors(configFileErrors); project.updateReferences(parsedCommandLine.projectReferences); const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); @@ -1738,7 +1818,7 @@ namespace ts.server { const configFileSpecs = project.configFileSpecs!; // TODO: GH#18217 const configFileName = project.getConfigFilePath(); const fileNamesResult = getFileNamesFromConfigSpecs(configFileSpecs, getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); - project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); + project.updateErrorOnNoInputFiles(fileNamesResult); this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); } @@ -1747,7 +1827,7 @@ namespace ts.server { * Read the config file of the project again by clearing the cache and update the project graph */ /* @internal */ - reloadConfiguredProject(project: ConfiguredProject) { + reloadConfiguredProject(project: ConfiguredProject, reason: string) { // At this point, there is no reason to not have configFile in the host const host = project.getCachedDirectoryStructureHost(); @@ -1757,7 +1837,7 @@ namespace ts.server { this.logger.info(`Reloading configured project ${configFileName}`); // Load project from the disk - this.loadConfiguredProject(project); + this.loadConfiguredProject(project, reason); project.updateGraph(); this.sendConfigFileDiagEvent(project, configFileName); @@ -1923,18 +2003,97 @@ namespace ts.server { if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - const { fileName } = info; - info.fileWatcher = this.watchFactory.watchFilePath( - this.host, - fileName, - (fileName, eventKind, path) => this.onSourceFileChanged(fileName, eventKind, path), - PollingInterval.Medium, - info.path, - WatchType.ClosedScriptInfo - ); + const indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath( + this.host, + info.fileName, + (fileName, eventKind, path) => this.onSourceFileChanged(fileName, eventKind, path), + PollingInterval.Medium, + info.path, + WatchType.ClosedScriptInfo + ); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules) as Path); + } } } + private watchClosedScriptInfoInNodeModules(dir: Path): ScriptInfoInNodeModulesWatcher { + // Watch only directory + const existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + + const watchDir = dir + "/node_modules" as Path; + const watcher = this.watchFactory.watchDirectory( + this.host, + watchDir, + (fileOrDirectory) => { + const fileOrDirectoryPath = this.toPath(fileOrDirectory); + // Has extension + Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + this.refreshScriptInfosInDirectory(watchDir); + } + else { + const info = this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + this.refreshScriptInfo(info); + } + } + // Folder + else if (!hasExtension(fileOrDirectoryPath)) { + this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, + WatchDirectoryFlags.Recursive, + WatchType.NodeModulesForClosedScriptInfo + ); + const result: ScriptInfoInNodeModulesWatcher = { + close: () => { + if (result.refCount === 1) { + watcher.close(); + this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + } + + private getModifiedTime(info: ScriptInfo) { + return (this.host.getModifiedTime!(info.path) || missingFileModifiedTime).getTime(); + } + + private refreshScriptInfo(info: ScriptInfo) { + const mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + const eventKind = getFileWatcherEventKind(info.mTime!, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + } + + private refreshScriptInfosInDirectory(dir: Path) { + dir = dir + directorySeparator as Path; + this.filenameToScriptInfo.forEach(info => { + if (isScriptInfoWatchedFromNodeModules(info) && startsWith(info.path, dir)) { + this.refreshScriptInfo(info); + } + }); + } + private stopWatchingScriptInfo(info: ScriptInfo) { if (info.fileWatcher) { info.fileWatcher.close(); @@ -2031,7 +2190,6 @@ namespace ts.server { if (project.hasExternalProjectRef() && project.pendingReload === ConfigFileProgramReloadLevel.Full && !this.pendingProjectUpdates.has(project.getProjectName())) { - this.loadConfiguredProject(project); project.updateGraph(); } }); @@ -2063,7 +2221,7 @@ namespace ts.server { // as there is no need to load contents of the files from the disk // Reload Projects - this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, returnTrue); + this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, returnTrue, "User requested reload projects"); this.ensureProjectForOpenFiles(); } @@ -2074,7 +2232,8 @@ namespace ts.server { /*delayReload*/ true, ignoreIfNotRootOfInferredProject ? isRootOfInferredProject => isRootOfInferredProject : // Reload open files if they are root of inferred project - returnTrue // Reload all the open files impacted by config file + returnTrue, // Reload all the open files impacted by config file + "Change in config file detected" ); this.delayEnsureProjectForOpenFiles(); } @@ -2086,7 +2245,7 @@ namespace ts.server { * If the there is no existing project it just opens the configured project for the config file * reloadForInfo provides a way to filter out files to reload configured project for */ - private reloadConfiguredProjectForFiles(openFiles: Map, delayReload: boolean, shouldReloadProjectFor: (openFileValue: T) => boolean) { + private reloadConfiguredProjectForFiles(openFiles: Map, delayReload: boolean, shouldReloadProjectFor: (openFileValue: T) => boolean, reason: string) { const updatedProjects = createMap(); // try to reload config file for all open files openFiles.forEach((openFileValue, path) => { @@ -2107,11 +2266,12 @@ namespace ts.server { if (!updatedProjects.has(configFileName)) { if (delayReload) { project.pendingReload = ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; this.delayUpdateProjectGraph(project); } else { // reload from the disk - this.reloadConfiguredProject(project); + this.reloadConfiguredProject(project, reason); } updatedProjects.set(configFileName, true); } @@ -2198,7 +2358,8 @@ namespace ts.server { const configFileName = this.getConfigFileNameForFile(originalFileInfo); if (!configFileName) return undefined; - const configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createAndLoadConfiguredProject(configFileName); + const configuredProject = this.findConfiguredProjectByProjectName(configFileName) || + this.createAndLoadConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName} for location: ${location.fileName}`); updateProjectIfDirty(configuredProject); // Keep this configured project as referenced from project addOriginalConfiguredProject(configuredProject); @@ -2248,7 +2409,7 @@ namespace ts.server { if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createLoadAndUpdateConfiguredProject(configFileName); + project = this.createLoadAndUpdateConfiguredProject(configFileName, `Creating possible configured project for ${fileName} to open`); // Send the event only if the project got created as part of this open request and info is part of the project if (info.isOrphan()) { // Since the file isnt part of configured project, do not send config file info @@ -2560,13 +2721,13 @@ namespace ts.server { if (fileExtensionIs(baseName, "js")) { const inferredTypingName = removeFileExtension(baseName); const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); - if (this.legacySafelist[cleanedTypingName]) { + const typeName = this.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { this.logger.info(`Excluded '${normalizedNames[i]}' because it matched ${cleanedTypingName} from the legacy safelist`); excludedFiles.push(normalizedNames[i]); // *exclude* it from the project... exclude = true; // ... but *include* it in the list of types to acquire - const typeName = this.legacySafelist[cleanedTypingName]; // Same best-effort dedupe as above if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); @@ -2689,8 +2850,8 @@ namespace ts.server { if (!project) { // errors are stored in the project, do not need to update the graph project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? - this.createConfiguredProjectWithDelayLoad(tsconfigFile) : - this.createLoadAndUpdateConfiguredProject(tsconfigFile); + this.createConfiguredProjectWithDelayLoad(tsconfigFile, `Creating configured project in external project: ${proj.projectFileName}`) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile, `Creating configured project in external project: ${proj.projectFileName}`); } if (project && !contains(exisingConfigFiles, tsconfigFile)) { // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project diff --git a/src/server/project.ts b/src/server/project.ts index f20530c88a9..29aafccccbb 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -254,6 +254,11 @@ namespace ts.server { installPackage(options: InstallPackageOptions): Promise { return this.typingsCache.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }); } + /* @internal */ + inspectValue(options: InspectValueOptions): Promise { + return this.typingsCache.inspectValue(options); + } + private get typingsCache(): TypingsCache { return this.projectService.typingsCache; } @@ -352,6 +357,10 @@ namespace ts.server { return this.projectService.host.readFile(fileName); } + writeFile(fileName: string, content: string): void { + return this.projectService.host.writeFile(fileName, content); + } + fileExists(file: string): boolean { // As an optimization, don't hit the disks for files we already know don't exist // (because we're watching for their creation). @@ -574,7 +583,7 @@ namespace ts.server { for (const f of this.program.getSourceFiles()) { this.detachScriptInfoIfNotRoot(f.fileName); } - const projectReferences = this.program.getProjectReferences(); + const projectReferences = this.program.getResolvedProjectReferences(); if (projectReferences) { for (const ref of projectReferences) { if (ref) { @@ -653,7 +662,7 @@ namespace ts.server { return this.rootFiles; } return map(this.program.getSourceFiles(), sourceFile => { - const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); Debug.assert(!!scriptInfo, "getScriptInfo", () => `scriptInfo for a file '${sourceFile.fileName}' Path: '${sourceFile.path}' / '${sourceFile.resolvedPath}' is missing.`); return scriptInfo!; }); @@ -1311,10 +1320,15 @@ namespace ts.server { /* @internal */ pendingReload: ConfigFileProgramReloadLevel; + /* @internal */ + pendingReloadReason: string | undefined; /*@internal*/ configFileSpecs: ConfigFileSpecs | undefined; + /*@internal*/ + canConfigFileJsonReportNoInputFiles: boolean; + /** Ref count to the project when opened from external project */ private externalProjectRefCount = 0; @@ -1327,6 +1341,9 @@ namespace ts.server { protected isInitialLoadPending: () => boolean = returnTrue; + /*@internal*/ + sendLoadingProjectFinish = false; + /*@internal*/ constructor(configFileName: NormalizedPath, projectService: ProjectService, @@ -1359,12 +1376,15 @@ namespace ts.server { result = this.projectService.reloadFileNamesOfConfiguredProject(this); break; case ConfigFileProgramReloadLevel.Full: - this.projectService.reloadConfiguredProject(this); + const reason = Debug.assertDefined(this.pendingReloadReason); + this.pendingReloadReason = undefined; + this.projectService.reloadConfiguredProject(this, reason); result = true; break; default: result = super.updateGraph(); } + this.projectService.sendProjectLoadingFinishEvent(this); this.projectService.sendProjectTelemetry(this); this.projectService.sendSurveyReady(this); return result; @@ -1390,7 +1410,7 @@ namespace ts.server { /*@internal*/ getResolvedProjectReferences() { const program = this.getCurrentProgram(); - return program && program.getProjectReferences(); + return program && program.getResolvedProjectReferences(); } enablePlugins() { @@ -1531,13 +1551,8 @@ namespace ts.server { } /*@internal*/ - updateErrorOnNoInputFiles(hasFileNames: boolean) { - if (hasFileNames) { - filterMutate(this.projectErrors!, error => !isErrorNoInputFiles(error)); // TODO: GH#18217 - } - else if (!this.configFileSpecs!.filesSpecs && !some(this.projectErrors, isErrorNoInputFiles)) { // TODO: GH#18217 - this.projectErrors!.push(getErrorForNoInputFiles(this.configFileSpecs!, this.getConfigFilePath())); - } + updateErrorOnNoInputFiles(fileNameResult: ExpandResult) { + updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs!, this.projectErrors!, this.canConfigFileJsonReportNoInputFiles); } } diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 5c6d9bed337..14b2fa7c43c 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -1087,16 +1087,17 @@ namespace ts.server.protocol { /** * Information about the item to be renamed. */ - export interface RenameInfo { + export type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + export interface RenameInfoSuccess { /** * True if item can be renamed. */ - canRename: boolean; - + canRename: true; /** - * Error message if item can not be renamed. + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ - localizedErrorMessage?: string; + fileToRename?: string; /** * Display name of the item to be renamed. @@ -1117,6 +1118,16 @@ namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + export interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; } /** @@ -1126,7 +1137,12 @@ namespace ts.server.protocol { /** The file to which the spans apply */ file: string; /** The text spans in this group */ - locs: TextSpan[]; + locs: RenameTextSpan[]; + } + + export interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; } export interface RenameResponseBody { @@ -2436,6 +2452,30 @@ namespace ts.server.protocol { openFiles: string[]; } + export type ProjectLoadingStartEventName = "projectLoadingStart"; + export interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + + export interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + + export type ProjectLoadingFinishEventName = "projectLoadingFinish"; + export interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + + export interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + export type SurveyReadyEventName = "surveyReady"; export interface SurveyReadyEvent extends Event { @@ -2728,6 +2768,14 @@ namespace ts.server.protocol { payload: TypingsInstalledTelemetryEventPayload; } +/* __GDPR__ + "typingsinstalled" : { + "${include}": ["${TypeScriptCommonProperties}"], + "installedPackages": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, + "installSuccess": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + "typingsInstallerVersion": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } + } + */ export interface TypingsInstalledTelemetryEventPayload { /** * Comma separated list of installed typing packages diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 085dd6d0eef..5434e76072c 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -167,7 +167,7 @@ namespace ts.server { const fileName = tempFileName || this.fileName; const getText = () => text === undefined ? (text = this.host.readFile(fileName) || "") : text; // Only non typescript files have size limitation - if (!hasTypeScriptFileExtension(this.fileName)) { + if (!hasTSFileExtension(this.fileName)) { const fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > maxFileSize) { Debug.assert(!!this.info.containingProjects.length); @@ -250,6 +250,9 @@ namespace ts.server { /*@internal*/ cacheSourceFile: DocumentRegistrySourceFileCache; + /*@internal*/ + mTime?: number; + constructor( private readonly host: ServerHost, readonly fileName: NormalizedPath, diff --git a/src/server/session.ts b/src/server/session.ts index 5d364abc757..efd369edb69 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -336,16 +336,23 @@ namespace ts.server { function combineProjectOutputForReferences(projects: Projects, defaultProject: Project, initialLocation: sourcemaps.SourceMappableLocation, projectService: ProjectService): ReadonlyArray { const outputs: ReferencedSymbol[] = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, ({ project, location }, tryAddToTodo) => { + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, ({ project, location }, getMappedLocation) => { for (const outputReferencedSymbol of project.getLanguageService().findReferences(location.fileName, location.position) || emptyArray) { - let symbolToAddTo = find(outputs, o => documentSpansEqual(o.definition, outputReferencedSymbol.definition)); + const mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + const definition: ReferencedSymbolDefinitionInfo = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : { + ...outputReferencedSymbol.definition, + textSpan: createTextSpan(mappedDefinitionFile.position, outputReferencedSymbol.definition.textSpan.length), + fileName: mappedDefinitionFile.fileName, + }; + let symbolToAddTo = find(outputs, o => documentSpansEqual(o.definition, definition)); if (!symbolToAddTo) { - symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + symbolToAddTo = { definition, references: [] }; outputs.push(symbolToAddTo); } for (const ref of outputReferencedSymbol.references) { - if (!contains(symbolToAddTo.references, ref, documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. + if (!contains(symbolToAddTo.references, ref, documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { symbolToAddTo.references.push(ref); } } @@ -373,12 +380,17 @@ namespace ts.server { } } + type CombineProjectOutputCallback = ( + where: ProjectAndLocation, + getMappedLocation: (project: Project, location: sourcemaps.SourceMappableLocation) => sourcemaps.SourceMappableLocation | undefined, + ) => void; + function combineProjectOutputWorker( projects: Projects, defaultProject: Project, initialLocation: TLocation, projectService: ProjectService, - cb: (where: ProjectAndLocation, getMappedLocation: (project: Project, location: sourcemaps.SourceMappableLocation) => boolean) => void, + cb: CombineProjectOutputCallback, getDefinition: (() => sourcemaps.SourceMappableLocation | undefined) | undefined, ): void { let toDo: ProjectAndLocation[] | undefined; @@ -417,13 +429,13 @@ namespace ts.server { projectService: ProjectService, toDo: ProjectAndLocation[] | undefined, seenProjects: Map, - cb: (where: ProjectAndLocation, getMappedLocation: (project: Project, location: sourcemaps.SourceMappableLocation) => boolean) => void, + cb: CombineProjectOutputCallback, ): ProjectAndLocation[] | undefined { if (projectAndLocation.project.getCancellationToken().isCancellationRequested()) return undefined; // Skip rest of toDo if cancelled cb(projectAndLocation, (project, location) => { seenProjects.set(projectAndLocation.project.projectName, true); const originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); - if (!originalLocation) return false; + if (!originalLocation) return undefined; const originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName)!; toDo = toDo || []; @@ -437,7 +449,7 @@ namespace ts.server { for (const symlinkedProject of symlinkedProjects) addToTodo({ project: symlinkedProject, location: originalLocation as TLocation }, toDo!, seenProjects); }); } - return true; + return originalLocation; }); return toDo; } @@ -478,6 +490,7 @@ namespace ts.server { globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; + typesMapLocation?: string; } export class Session implements EventSender { @@ -538,6 +551,7 @@ namespace ts.server { globalPlugins: opts.globalPlugins, pluginProbeLocations: opts.pluginProbeLocations, allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, syntaxOnly: opts.syntaxOnly, }; this.projectService = new ProjectService(settings); @@ -554,9 +568,19 @@ namespace ts.server { const { openFiles } = event.data; this.projectsUpdatedInBackgroundEvent(openFiles); break; + case ProjectLoadingStartEvent: + const { project, reason } = event.data; + this.event( + { projectName: project.getProjectName(), reason }, + ProjectLoadingStartEvent); + break; + case ProjectLoadingFinishEvent: + const { project: finishProject } = event.data; + this.event({ projectName: finishProject.getProjectName() }, ProjectLoadingStartEvent); + break; case LargeFileReferencedEvent: const { file, fileSize, maxFileSize } = event.data; - this.event({ file, fileSize, maxFileSize }, "largeFileReferenced"); + this.event({ file, fileSize, maxFileSize }, LargeFileReferencedEvent); break; case ConfigFileDiagEvent: const { triggerFile, configFileName: configFile, diagnostics } = event.data; @@ -565,14 +589,14 @@ namespace ts.server { triggerFile, configFile, diagnostics: bakedDiags - }, "configFileDiag"); + }, ConfigFileDiagEvent); break; case SurveyReady: const { surveyId } = event.data; - this.event({ surveyId }, "surveyReady"); + this.event({ surveyId }, SurveyReady); break; case ProjectLanguageServiceStateEvent: { - const eventName: protocol.ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + const eventName: protocol.ProjectLanguageServiceStateEventName = ProjectLanguageServiceStateEvent; this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled @@ -603,11 +627,15 @@ namespace ts.server { // Send project changed event this.event({ openFiles - }, "projectsUpdatedInBackground"); + }, ProjectsUpdatedInBackgroundEvent); } } - public logError(err: Error, cmd: string) { + public logError(err: Error, cmd: string): void { + this.logErrorWorker(err, cmd); + } + + private logErrorWorker(err: Error, cmd: string, fileRequest?: protocol.FileRequestArgs): void { let msg = "Exception on executing command " + cmd; if (err.message) { msg += ":\n" + indent(err.message); @@ -615,6 +643,19 @@ namespace ts.server { msg += "\n" + indent((err).stack!); } } + + if (fileRequest && this.logger.hasLevel(LogLevel.verbose)) { + try { + const { file, project } = this.getFileAndProject(fileRequest); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + const text = getSnapshotText(scriptInfo.getSnapshot()); + msg += `\n\nFile text of ${fileRequest.file}:${indent(text)}\n`; + } + } + catch {} // tslint:disable-line no-empty + } + this.logger.msg(msg, Msg.Err); } @@ -1096,7 +1137,7 @@ namespace ts.server { return projectInfo; } - private getRenameInfo(args: protocol.FileLocationRequestArgs) { + private getRenameInfo(args: protocol.FileLocationRequestArgs): RenameInfo { const { file, project } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); return project.getLanguageService().getRenameInfo(file, position); @@ -1149,21 +1190,28 @@ namespace ts.server { if (!simplifiedResult) return locations; const defaultProject = this.getDefaultProject(args); - const renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + const renameInfo: protocol.RenameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; } - // strips 'triggerSpan' - private static mapRenameInfo({ canRename, localizedErrorMessage, displayName, fullDisplayName, kind, kindModifiers }: RenameInfo): protocol.RenameInfo { - return { canRename, localizedErrorMessage, displayName, fullDisplayName, kind, kindModifiers }; + private mapRenameInfo(info: RenameInfo, scriptInfo: ScriptInfo): protocol.RenameInfo { + if (info.canRename) { + const { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan } = info; + return identity( + { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }); + } + else { + return info; + } } private toSpanGroups(locations: ReadonlyArray): ReadonlyArray { const map = createMap(); - for (const { fileName, textSpan } of locations) { + for (const { fileName, textSpan, originalTextSpan: _, originalFileName: _1, ...prefixSuffixText } of locations) { let group = map.get(fileName); if (!group) map.set(fileName, group = { file: fileName, locs: [] }); - group.locs.push(this.toLocationTextSpan(textSpan, Debug.assertDefined(this.projectService.getScriptInfo(fileName)))); + const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(fileName)); + group.locs.push({ ...this.toLocationTextSpan(textSpan, scriptInfo), ...prefixSuffixText }); } return arrayFrom(map.values()); } @@ -1818,8 +1866,8 @@ namespace ts.server { private applyCodeActionCommand(args: protocol.ApplyCodeActionCommandRequestArgs): {} { const commands = args.command as CodeActionCommand | CodeActionCommand[]; // They should be sending back the command we sent them. for (const command of toArray(commands)) { - const { project } = this.getFileAndProject(command); - project.getLanguageService().applyCodeActionCommand(command).then( + const { file, project } = this.getFileAndProject(command); + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then( _result => { /* TODO: GH#20447 report success message? */ }, _error => { /* TODO: GH#20447 report errors */ }); } @@ -2310,8 +2358,10 @@ namespace ts.server { } let request: protocol.Request | undefined; + let relevantFile: protocol.FileRequestArgs | undefined; try { request = JSON.parse(message); + relevantFile = request.arguments && (request as protocol.FileRequest).arguments.file ? (request as protocol.FileRequest).arguments : undefined; const { response, responseRequired } = this.executeCommand(request); if (this.logger.hasLevel(LogLevel.requestTime)) { @@ -2337,7 +2387,7 @@ namespace ts.server { this.doOutput({ canceled: true }, request!.command, request!.seq, /*success*/ true); return; } - this.logError(err, message); + this.logErrorWorker(err, message, relevantFile); this.doOutput( /*info*/ undefined, request ? request.command : CommandNames.Unknown, diff --git a/src/server/typingsCache.ts b/src/server/typingsCache.ts index 12b2303cfd3..64a117bbe25 100644 --- a/src/server/typingsCache.ts +++ b/src/server/typingsCache.ts @@ -8,6 +8,8 @@ namespace ts.server { export interface ITypingsInstaller { isKnownTypesPackageName(name: string): boolean; installPackage(options: InstallPackageOptionsWithProject): Promise; + /* @internal */ + inspectValue(options: InspectValueOptions): Promise; enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray | undefined): void; attach(projectService: ProjectService): void; onProjectClosed(p: Project): void; @@ -18,6 +20,7 @@ namespace ts.server { isKnownTypesPackageName: returnFalse, // Should never be called because we never provide a types registry. installPackage: notImplemented, + inspectValue: notImplemented, enqueueInstallTypingsRequest: noop, attach: noop, onProjectClosed: noop, @@ -95,6 +98,10 @@ namespace ts.server { return this.installer.installPackage(options); } + inspectValue(options: InspectValueOptions): Promise { + return this.installer.inspectValue(options); + } + enqueueInstallTypingsForProject(project: Project, unresolvedImports: SortedReadonlyArray | undefined, forceRefresh: boolean) { const typeAcquisition = project.getTypeAcquisition(); diff --git a/src/server/utilities.ts b/src/server/utilities.ts index 615361cdcd8..d6cfe269c8d 100644 --- a/src/server/utilities.ts +++ b/src/server/utilities.ts @@ -246,14 +246,16 @@ namespace ts.server { return index === 0 || value !== array[index - 1]; } + const indentStr = "\n "; + /* @internal */ export function indent(str: string): string { - return "\n " + str; + return indentStr + str.replace(/\n/g, indentStr); } /** Put stringified JSON on the next line, indented. */ /* @internal */ export function stringifyIndented(json: {}): string { - return "\n " + JSON.stringify(json); + return indentStr + JSON.stringify(json); } } diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index c2041179888..78e10ce2044 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -138,7 +138,7 @@ namespace ts.codefix { default: { // Don't try to declare members in JavaScript files - if (isSourceFileJavaScript(sourceFile)) { + if (isSourceFileJS(sourceFile)) { return; } const prop = createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 76cdf471466..676a5fb1795 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -2,42 +2,37 @@ namespace ts.codefix { const fixId = "convertToAsyncFunction"; const errorCodes = [Diagnostics.This_may_be_converted_to_an_async_function.code]; + let codeActionSucceeded = true; registerCodeFix({ errorCodes, getCodeActions(context: CodeFixContext) { + codeActionSucceeded = true; const changes = textChanges.ChangeTracker.with(context, (t) => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context)); - return [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_async_function, fixId, Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_async_function, fixId, Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context)), }); - - /* - custom type to encapsulate information for variable declarations synthesized in the refactor - numberOfUsesOriginal - number of times the variable should be assigned in the refactor - numberOfUsesSynthesized - count of how many times the variable has been assigned so far - At the end of the refactor, numberOfUsesOriginal should === numberOfUsesSynthesized - */ interface SynthIdentifier { - identifier: Identifier; - types: Type[]; - numberOfAssignmentsOriginal: number; + readonly identifier: Identifier; + readonly types: Type[]; + numberOfAssignmentsOriginal: number; // number of times the variable should be assigned in the refactor } interface SymbolAndIdentifier { - identifier: Identifier; - symbol: Symbol; + readonly identifier: Identifier; + readonly symbol: Symbol; } interface Transformer { - checker: TypeChecker; - synthNamesMap: Map; // keys are the symbol id of the identifier - allVarNames: SymbolAndIdentifier[]; - setOfExpressionsToReturn: Map; // keys are the node ids of the expressions - constIdentifiers: Identifier[]; - originalTypeMap: Map; // keys are the node id of the identifier - isInJSFile: boolean; + readonly checker: TypeChecker; + readonly synthNamesMap: Map; // keys are the symbol id of the identifier + readonly allVarNames: ReadonlyArray; + readonly setOfExpressionsToReturn: ReadonlyMap; // keys are the node ids of the expressions + readonly constIdentifiers: Identifier[]; + readonly originalTypeMap: ReadonlyMap; // keys are the node id of the identifier + readonly isInJSFile: boolean; } function convertToAsyncFunction(changes: textChanges.ChangeTracker, sourceFile: SourceFile, position: number, checker: TypeChecker, context: CodeFixContextBase): void { @@ -61,19 +56,19 @@ namespace ts.codefix { const synthNamesMap: Map = createMap(); const originalTypeMap: Map = createMap(); const allVarNames: SymbolAndIdentifier[] = []; - const isInJSFile = isInJavaScriptFile(functionToConvert); + const isInJavascript = isInJSFile(functionToConvert); const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); const functionToConvertRenamed: FunctionLikeDeclaration = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); const constIdentifiers = getConstIdentifiers(synthNamesMap); const returnStatements = getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - const transformer = { checker, synthNamesMap, allVarNames, setOfExpressionsToReturn, constIdentifiers, originalTypeMap, isInJSFile }; + const transformer: Transformer = { checker, synthNamesMap, allVarNames, setOfExpressionsToReturn, constIdentifiers, originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, SyntaxKind.AsyncKeyword, functionToConvert); + changes.insertLastModifierBefore(sourceFile, SyntaxKind.AsyncKeyword, functionToConvert); function startTransformation(node: CallExpression, nodeToReplace: Node) { const newNodes = transformExpression(node, transformer, node); @@ -81,24 +76,19 @@ namespace ts.codefix { } for (const statement of returnStatements) { - if (isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - forEachChild(statement, function visit(node: Node) { - if (isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!isFunctionLike(node)) { - forEachChild(node, visit); - } - }); - } + forEachChild(statement, function visit(node) { + if (isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!isFunctionLike(node)) { + forEachChild(node, visit); + } + }); } } // Returns the identifiers that are never reassigned in the refactor - function getConstIdentifiers(synthNamesMap: Map): Identifier[] { + function getConstIdentifiers(synthNamesMap: ReadonlyMap): Identifier[] { const constIdentifiers: Identifier[] = []; synthNamesMap.forEach((val) => { if (val.numberOfAssignmentsOriginal === 0) { @@ -165,6 +155,7 @@ namespace ts.codefix { function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker: TypeChecker, synthNamesMap: Map, context: CodeFixContextBase, setOfAllExpressionsToReturn: Map, originalType: Map, allVarNames: SymbolAndIdentifier[]): FunctionLikeDeclaration { const identsToRenameMap: Map = createMap(); // key is the symbol id + const collidingSymbolMap: Map = createMap(); forEachChild(nodeToRename, function visit(node: Node) { if (!isIdentifier(node)) { forEachChild(node, visit); @@ -181,20 +172,26 @@ namespace ts.codefix { // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - const synthName = getNewNameIfConflict(createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + const firstParameter = firstOrUndefined(lastCallSignature.parameters); + const ident = firstParameter && isParameter(firstParameter.valueDeclaration) && tryCast(firstParameter.valueDeclaration.name, isIdentifier) || createOptimisticUniqueName("result"); + const synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent))) { + const originalName = node.text; + const collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(ident => ident.identifier.text === node.text && ident.symbol !== symbol)) { - const newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(prevSymbol => prevSymbol !== symbol)) { + const newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { const identifier = getSynthesizedDeepClone(node); @@ -202,6 +199,7 @@ namespace ts.codefix { synthNamesMap.set(symbolIdString, { identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(elem => elem.identifier.text === node.text).length/*, numberOfAssignmentsSynthesized: 0*/ }); if ((isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || isVariableDeclaration(node.parent)) { allVarNames.push({ identifier, symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -229,9 +227,7 @@ namespace ts.codefix { if (renameInfo) { const type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(getNodeId(clone).toString(), type); - } + originalType.set(getNodeId(clone).toString(), type); } } @@ -244,17 +240,27 @@ namespace ts.codefix { } - function getNewNameIfConflict(name: Identifier, allVarNames: SymbolAndIdentifier[]): SynthIdentifier { - const numVarsSameName = allVarNames.filter(elem => elem.identifier.text === name.text).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap: Map, originalName: string, symbol: Symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName)!.push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + + function getNewNameIfConflict(name: Identifier, originalNames: ReadonlyMap): SynthIdentifier { + const numVarsSameName = (originalNames.get(name.text) || emptyArray).length; const numberOfAssignmentsOriginal = 0; const identifier = numVarsSameName === 0 ? name : createIdentifier(name.text + "_" + numVarsSameName); return { identifier, types: [], numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring - function transformExpression(node: Expression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): Statement[] { + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts + function transformExpression(node: Expression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): ReadonlyArray { if (!node) { - return []; + return emptyArray; } const originalType = isIdentifier(node) && transformer.originalTypeMap.get(getNodeId(node).toString()); @@ -273,10 +279,11 @@ namespace ts.codefix { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return emptyArray; } - function transformCatch(node: CallExpression, transformer: Transformer, prevArgName?: SynthIdentifier): Statement[] { + function transformCatch(node: CallExpression, transformer: Transformer, prevArgName?: SynthIdentifier): ReadonlyArray { const func = node.arguments[0]; const argName = getArgName(func, transformer); const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(node).toString()); @@ -290,20 +297,21 @@ namespace ts.codefix { prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach((val, key) => { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + const newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(elem => elem.text === prevArgName.identifier.text)) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } const tryBlock = createBlock(transformExpression(node.expression, transformer, node, prevArgName)); const transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - const catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + const catchArg = argName ? argName.identifier.text : "e"; const catchClause = createCatchClause(catchArg, createBlock(transformationBody)); /* @@ -322,7 +330,13 @@ namespace ts.codefix { return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } - function transformThen(node: CallExpression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): Statement[] { + function createUniqueSynthName(prevArgName: SynthIdentifier) { + const renamedPrevArg = createOptimisticUniqueName(prevArgName.identifier.text); + const newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } + + function transformThen(node: CallExpression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): ReadonlyArray { const [res, rej] = node.arguments; if (!res) { @@ -339,79 +353,95 @@ namespace ts.codefix { const transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - const catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + const catchArg = argNameRej ? argNameRej.identifier.text : "e"; const catchClause = createCatchClause(catchArg, createBlock(transformationBody2)); - return [createTry(tryBlock, catchClause, /* finallyBlock */ undefined) as Statement]; - } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + return [createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } - function getFlagOfIdentifier(node: Identifier, constIdentifiers: Identifier[]): NodeFlags { + function getFlagOfIdentifier(node: Identifier, constIdentifiers: ReadonlyArray): NodeFlags { const inArr: boolean = constIdentifiers.some(elem => elem.text === node.text); return inArr ? NodeFlags.Const : NodeFlags.Let; } - function transformPromiseCall(node: Expression, transformer: Transformer, prevArgName?: SynthIdentifier): Statement[] { + function transformPromiseCall(node: Expression, transformer: Transformer, prevArgName?: SynthIdentifier): ReadonlyArray { const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - const hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; const originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName!, createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || isPropertyAccessExpression(originalNodeParent))) { return [createStatement(createAwait(node))]; } return [createReturn(getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName: SynthIdentifier, rightHandSide: Expression, transformer: Transformer): NodeArray { - - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return createNodeArray([createStatement(createAssignment(getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName: SynthIdentifier | undefined, rightHandSide: Expression, transformer: Transformer): ReadonlyArray { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [createStatement(rightHandSide)]; } - return createNodeArray([createVariableStatement(/*modifiers*/ undefined, - (createVariableDeclarationList([createVariableDeclaration(getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [createStatement(createAssignment(getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + + return [createVariableStatement(/*modifiers*/ undefined, + (createVariableDeclarationList([createVariableDeclaration(getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } - function getTransformationBody(func: Node, prevArgName: SynthIdentifier | undefined, argName: SynthIdentifier, parent: CallExpression, transformer: Transformer): NodeArray { + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts + function getTransformationBody(func: Expression, prevArgName: SynthIdentifier | undefined, argName: SynthIdentifier | undefined, parent: CallExpression, transformer: Transformer): ReadonlyArray { - const hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - const hasArgName = argName && argName.identifier.text.length > 0; const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(parent).toString()); switch (func.kind) { - case SyntaxKind.Identifier: - if (!hasArgName) break; - - const synthCall = createCall(getSynthesizedDeepClone(func) as Identifier, /*typeArguments*/ undefined, [argName.identifier]); - if (shouldReturn) { - return createNodeArray([createReturn(synthCall)]); + case SyntaxKind.NullKeyword: + // do not produce a transformed statement for a null argument + break; + case SyntaxKind.Identifier: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler + break; } - if (!hasPrevArgName) break; + const synthCall = createCall(getSynthesizedDeepClone(func as Identifier), /*typeArguments*/ undefined, [argName.identifier]); + if (shouldReturn) { + return [createReturn(synthCall)]; + } - const type = transformer.originalTypeMap.get(getNodeId(func).toString()); - const callSignatures = type && transformer.checker.getSignaturesOfType(type, SignatureKind.Call); - const returnType = callSignatures && callSignatures[0].getReturnType(); - const varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName!, createAwait(synthCall), transformer); - prevArgName!.types.push(returnType!); + const type = transformer.originalTypeMap.get(getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + const callSignatures = transformer.checker.getSignaturesOfType(type, SignatureKind.Call); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; + break; + } + const returnType = callSignatures[0].getReturnType(); + const varDeclOrAssignment = createTransformedStatement(prevArgName, createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: + case SyntaxKind.ArrowFunction: { + const funcBody = (func as FunctionExpression | ArrowFunction).body; // Arrow functions with block bodies { } will enter this control flow - if (isFunctionLikeDeclaration(func) && func.body && isBlock(func.body) && func.body.statements) { + if (isBlock(funcBody)) { let refactoredStmts: Statement[] = []; + let seenReturnStatement = false; + + for (const statement of funcBody.statements) { + if (isReturnStatement(statement)) { + seenReturnStatement = true; + } - for (const statement of func.body.statements) { if (getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -420,47 +450,64 @@ namespace ts.codefix { } } - return shouldReturn ? getSynthesizedDeepClones(createNodeArray(refactoredStmts)) : - removeReturns(createNodeArray(refactoredStmts), prevArgName!.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(s => getSynthesizedDeepClone(s)) : + removeReturns( + refactoredStmts, + prevArgName === undefined ? undefined : prevArgName.identifier, + transformer, + seenReturnStatement); } else { - const funcBody = (func).body; - const innerRetStmts = getReturnStatementsWithPromiseHandlers(createReturn(funcBody as Expression)); + const innerRetStmts = getReturnStatementsWithPromiseHandlers(createReturn(funcBody)); const innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - const type = transformer.checker.getTypeAtLocation(func); - const returnType = getLastCallSignature(type, transformer.checker).getReturnType(); - const varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName!, getSynthesizedDeepClone(funcBody) as Expression, transformer); - prevArgName!.types.push(returnType); - return varDeclOrAssignment; + const type = transformer.checker.getTypeAtLocation(func); + const returnType = getLastCallSignature(type, transformer.checker)!.getReturnType(); + const rightHandSide = getSynthesizedDeepClone(funcBody); + const possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType) ? createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + const transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } + return transformedStatement; } else { - return createNodeArray([createReturn(getSynthesizedDeepClone(funcBody) as Expression)]); + return [createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return createNodeArray([]); + return emptyArray; } - function getLastCallSignature(type: Type, checker: TypeChecker): Signature { - const callSignatures = type && checker.getSignaturesOfType(type, SignatureKind.Call); - return callSignatures && callSignatures[callSignatures.length - 1]; + function getLastCallSignature(type: Type, checker: TypeChecker): Signature | undefined { + const callSignatures = checker.getSignaturesOfType(type, SignatureKind.Call); + return lastOrUndefined(callSignatures); } - function removeReturns(stmts: NodeArray, prevArgName: Identifier, constIdentifiers: Identifier[]): NodeArray { + function removeReturns(stmts: ReadonlyArray, prevArgName: Identifier | undefined, transformer: Transformer, seenReturnStatement: boolean): ReadonlyArray { const ret: Statement[] = []; for (const stmt of stmts) { if (isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(createVariableStatement(/*modifiers*/ undefined, - (createVariableDeclarationList([createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + const possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(createVariableStatement(/*modifiers*/ undefined, + (createVariableDeclarationList([createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { @@ -468,15 +515,21 @@ namespace ts.codefix { } } - return createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(createVariableStatement(/*modifiers*/ undefined, + (createVariableDeclarationList([createVariableDeclaration(prevArgName, /*type*/ undefined, createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + + return ret; } - function getInnerTransformationBody(transformer: Transformer, innerRetStmts: Node[], prevArgName?: SynthIdentifier) { + function getInnerTransformationBody(transformer: Transformer, innerRetStmts: ReadonlyArray, prevArgName?: SynthIdentifier) { let innerCbBody: Statement[] = []; for (const stmt of innerRetStmts) { - forEachChild(stmt, function visit(node: Node) { + forEachChild(stmt, function visit(node) { if (isCallExpression(node)) { const temp = transformExpression(node, transformer, node, prevArgName); innerCbBody = innerCbBody.concat(temp); @@ -492,15 +545,7 @@ namespace ts.codefix { return innerCbBody; } - function hasPropertyAccessExpressionWithName(node: CallExpression, funcName: string): boolean { - if (!isPropertyAccessExpression(node.expression)) { - return false; - } - - return node.expression.name.text === funcName; - } - - function getArgName(funcNode: Node, transformer: Transformer): SynthIdentifier { + function getArgName(funcNode: Expression, transformer: Transformer): SynthIdentifier | undefined { const numberOfAssignmentsOriginal = 0; const types: Type[] = []; @@ -510,23 +555,21 @@ namespace ts.codefix { if (isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { const param = funcNode.parameters[0].name as Identifier; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (isCallExpression(funcNode) && funcNode.arguments.length > 0 && isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0] as Identifier, types, numberOfAssignmentsOriginal }; - } else if (isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: createIdentifier(""), types, numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier: Identifier): SynthIdentifier { + function getMapEntryOrDefault(identifier: Identifier): SynthIdentifier { const originalNode = getOriginalNode(identifier); const symbol = getSymbol(originalNode); @@ -546,4 +589,4 @@ namespace ts.codefix { return node.original ? node.original : node; } } -} \ No newline at end of file +} diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index c81446152dd..4cdd7eb42d2 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -12,7 +12,7 @@ namespace ts.codefix { getCodeActions(context) { const { sourceFile, program, span, host, formatContext } = context; - if (!isInJavaScriptFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index a23cb621608..dda0903562a 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -20,7 +20,7 @@ namespace ts.codefix { const { parentDeclaration, declSourceFile, inJs, makeStatic, token, call } = info; const methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); const addMember = inJs && !isInterfaceDeclaration(parentDeclaration) ? - singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return concatenate(singleElementArray(methodCodeAction), addMember); }, @@ -131,7 +131,7 @@ namespace ts.codefix { if (classOrInterface) { const makeStatic = ((leftExpressionType as TypeReference).target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); const declSourceFile = classOrInterface.getSourceFile(); - const inJs = isSourceFileJavaScript(declSourceFile); + const inJs = isSourceFileJS(declSourceFile); const call = tryCast(parent.parent, isCallExpression); return { kind: InfoKind.ClassOrInterface, token, parentDeclaration: classOrInterface, makeStatic, declSourceFile, inJs, call }; } @@ -142,7 +142,7 @@ namespace ts.codefix { return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): CodeFixAction | undefined { + function getActionsForAddMissingMemberInJavascriptFile(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): CodeFixAction | undefined { const changes = textChanges.ChangeTracker.with(context, t => addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic)); return changes.length === 0 ? undefined : createCodeFixAction(fixName, changes, [makeStatic ? Diagnostics.Initialize_static_property_0 : Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, Diagnostics.Add_all_missing_members); diff --git a/src/services/codefixes/fixCannotFindModule.ts b/src/services/codefixes/fixCannotFindModule.ts index 68fa3a5c030..1c7070c74bf 100644 --- a/src/services/codefixes/fixCannotFindModule.ts +++ b/src/services/codefixes/fixCannotFindModule.ts @@ -1,6 +1,9 @@ /* @internal */ namespace ts.codefix { - const fixId = "fixCannotFindModule"; + const fixName = "fixCannotFindModule"; + const fixIdInstallTypesPackage = "installTypesPackage"; + const fixIdGenerateTypes = "generateTypes"; + const errorCodeCannotFindModule = Diagnostics.Cannot_find_module_0.code; const errorCodes = [ errorCodeCannotFindModule, @@ -10,26 +13,141 @@ namespace ts.codefix { errorCodes, getCodeActions: context => { const { host, sourceFile, span: { start } } = context; - const packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [createCodeFixAction(fixId, /*changes*/ [], [Diagnostics.Install_0, packageName], fixId, Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + const packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) return undefined; + const typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [createCodeFixAction(fixName, /*changes*/ [], [Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: context => { + let savedTypesDir: string | null | undefined = null; // tslint:disable-line no-null-keyword + return codeFixAll(context, errorCodes, (changes, diag, commands) => { + const packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + const pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + const typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + const command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) commands.push(command); + break; + } + default: + Debug.fail(`Bad fixId: ${context.fixId}`); + } + }); }, - fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (_, diag, commands) => { - const pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }), }); - function getCommand(fileName: string, packageName: string): InstallPackageAction { + function tryGetGenerateTypesAction(context: CodeFixContextBase, packageName: string): CodeFixAction | undefined { + let command: GenerateTypesAction | undefined; + const changes = textChanges.ChangeTracker.with(context, t => { + const typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && createCodeFixAction(fixName, changes, [Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, Diagnostics.Generate_types_for_all_packages_without_types, command); + } + + function tryGenerateTypes(typesDir: string, packageName: string, context: CodeFixContextBase): GenerateTypesAction | undefined { + const file = context.sourceFile.fileName; + const fileToGenerateTypesFor = tryResolveJSModule(packageName, getDirectoryPath(file), context.host as ModuleResolutionHost); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) return undefined; + + const outputFileName = resolvePath(getDirectoryPath(context.program.getCompilerOptions().configFile!.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists!(outputFileName)) return undefined; + return { type: "generate types", file, fileToGenerateTypesFor, outputFileName }; + } + + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes: textChanges.ChangeTracker, context: CodeFixContextBase): string | undefined { + const { configFile } = context.program.getCompilerOptions(); + if (!configFile) return undefined; + + const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) return undefined; + + const compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + const newCompilerOptions = createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + + const compilerOptions = compilerOptionsProperty.initializer; + if (!isObjectLiteralExpression(compilerOptions)) return defaultTypesDirectoryName; + + const baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + const typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + + const defaultBaseUrl = "."; + function makeDefaultBaseUrl(): PropertyAssignment { + return createJsonPropertyAssignment("baseUrl", createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes: textChanges.ChangeTracker, tsconfig: TsConfigSourceFile, compilerOptions: ObjectLiteralExpression): string { + const baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + + const defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping(): PropertyAssignment { + return createJsonPropertyAssignment("*", createArrayLiteral([createStringLiteral(`${defaultTypesDirectoryName}/*`)])); + } + function makeDefaultPaths(): PropertyAssignment { + return createJsonPropertyAssignment("paths", createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes: textChanges.ChangeTracker, tsconfig: TsConfigSourceFile, compilerOptions: ObjectLiteralExpression) { + const paths = findProperty(compilerOptions, "paths"); + if (!paths || !isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + const existing = firstDefined(paths.initializer.properties, prop => + isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "*" && isArrayLiteralExpression(prop.initializer) + ? firstDefined(prop.initializer.elements, value => isStringLiteral(value) ? tryRemoveSuffix(value.text, "/*") : undefined) + : undefined); + if (existing) return existing; + + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + + function createJsonPropertyAssignment(name: string, initializer: Expression) { + return createPropertyAssignment(createStringLiteral(name), initializer); + } + + function findProperty(obj: ObjectLiteralExpression, name: string): PropertyAssignment | undefined { + return find(obj.properties, (p): p is PropertyAssignment => isPropertyAssignment(p) && !!p.name && isStringLiteral(p.name) && p.name.text === name); + } + + function getInstallCommand(fileName: string, packageName: string): InstallPackageAction { return { type: "install package", file: fileName, packageName }; } - function getTypesPackageNameToInstall(host: LanguageServiceHost, sourceFile: SourceFile, pos: number, diagCode: number): string | undefined { + function tryGetImportedPackageName(sourceFile: SourceFile, pos: number): string | undefined { const moduleName = cast(getTokenAtPosition(sourceFile, pos), isStringLiteral).text; - const { packageName } = getPackageName(moduleName); + const { packageName } = parsePackageName(moduleName); + return isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + + function getTypesPackageNameToInstall(packageName: string, host: LanguageServiceHost, diagCode: number): string | undefined { return diagCode === errorCodeCannotFindModule ? (JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName!(packageName) ? getTypesPackageName(packageName) : undefined); // TODO: GH#18217 diff --git a/src/services/codefixes/fixStrictClassInitialization.ts b/src/services/codefixes/fixStrictClassInitialization.ts index 0647a64c368..15c57c604dd 100644 --- a/src/services/codefixes/fixStrictClassInitialization.ts +++ b/src/services/codefixes/fixStrictClassInitialization.ts @@ -110,7 +110,7 @@ namespace ts.codefix { function getDefaultValueFromType (checker: TypeChecker, type: Type): Expression | undefined { if (type.flags & TypeFlags.BooleanLiteral) { - return type === checker.getFalseType() ? createFalse() : createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? createFalse() : createTrue(); } else if (type.isLiteral()) { return createLiteral(type.value); diff --git a/src/services/codefixes/generateTypes.ts b/src/services/codefixes/generateTypes.ts new file mode 100644 index 00000000000..6af72da562d --- /dev/null +++ b/src/services/codefixes/generateTypes.ts @@ -0,0 +1,227 @@ +/* @internal */ +namespace ts { + export function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string { + return valueInfoToDeclarationFileText(inspectValue(name, moduleValue), formatSettings); + } + + export function valueInfoToDeclarationFileText(valueInfo: ValueInfo, formatSettings: FormatCodeSettings): string { + return textChanges.getNewFileText(toStatements(valueInfo, OutputKind.ExportEquals), ScriptKind.TS, "\n", formatting.getFormatContext(formatSettings)); + } + + const enum OutputKind { ExportEquals, NamedExport, NamespaceMember } + function toNamespaceMemberStatements(info: ValueInfo): ReadonlyArray { + return toStatements(info, OutputKind.NamespaceMember); + } + function toStatements(info: ValueInfo, kind: OutputKind): ReadonlyArray { + const isDefault = info.name === InternalSymbolName.Default; + const name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== OutputKind.NamedExport) return emptyArray; + + const modifiers = isDefault && info.kind === ValueKind.FunctionOrClass ? [createModifier(SyntaxKind.ExportKeyword), createModifier(SyntaxKind.DefaultKeyword)] + : kind === OutputKind.ExportEquals ? [createModifier(SyntaxKind.DeclareKeyword)] + : kind === OutputKind.NamedExport ? [createModifier(SyntaxKind.ExportKeyword)] + : undefined; + const exportEquals = () => kind === OutputKind.ExportEquals ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : emptyArray; + const exportDefault = () => isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : emptyArray; + + switch (info.kind) { + case ValueKind.FunctionOrClass: + return [...exportEquals(), ...functionOrClassToStatements(modifiers, name, info)]; + case ValueKind.Object: + const { members } = info; + if (kind === OutputKind.ExportEquals) { + return flatMap(members, v => toStatements(v, OutputKind.NamedExport)); + } + if (members.some(m => m.kind === ValueKind.FunctionOrClass)) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return [...exportDefault(), createNamespace(modifiers, name, flatMap(members, toNamespaceMemberStatements))]; + } + // falls through + case ValueKind.Const: + case ValueKind.Array: { + const comment = info.kind === ValueKind.Const ? info.comment : undefined; + const constVar = createVariableStatement(modifiers, createVariableDeclarationList([createVariableDeclaration(name, toType(info))], NodeFlags.Const)); + return [...exportEquals(), ...exportDefault(), addComment(constVar, comment)]; + } + default: + return Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name: string, isExportEquals: boolean): ExportAssignment { + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, createIdentifier(name)); + } + + function functionOrClassToStatements(modifiers: Modifiers, name: string, { source, prototypeMembers, namespaceMembers }: ValueInfoFunctionOrClass): ReadonlyArray { + const fnAst = parseClassOrFunctionBody(source); + const { parameters, returnType } = fnAst === undefined ? { parameters: emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst); + const instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : emptyArray; + + const classStaticMembers: ClassElement[] | undefined = + instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === SyntaxKind.Constructor ? [] : undefined; + + const namespaceStatements = flatMap(namespaceMembers, info => { + if (!isValidIdentifier(info.name)) return undefined; + if (classStaticMembers) { + switch (info.kind) { + case ValueKind.Object: + if (info.members.some(m => m.kind === ValueKind.FunctionOrClass)) { + break; + } + // falls through + case ValueKind.Array: + case ValueKind.Const: + classStaticMembers.push( + addComment( + createProperty(/*decorators*/ undefined, [createModifier(SyntaxKind.StaticKeyword)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), + info.kind === ValueKind.Const ? info.comment : undefined)); + return undefined; + case ValueKind.FunctionOrClass: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + const sig = tryGetMethod(info, [createModifier(SyntaxKind.StaticKeyword)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, OutputKind.NamespaceMember); + }); + + const decl = classStaticMembers + ? createClassDeclaration( + /*decorators*/ undefined, + modifiers, + name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, + [ + ...classStaticMembers, + ...(parameters.length ? [createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : emptyArray), + ...instanceProperties, + // ignore non-functions on the prototype + ...mapDefined(prototypeMembers, info => info.kind === ValueKind.FunctionOrClass ? tryGetMethod(info) : undefined), + ]) + : createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl, ...(namespaceStatements.length === 0 ? emptyArray : [createNamespace(modifiers && modifiers.map(m => getSynthesizedDeepClone(m)), name, namespaceStatements)])]; + } + + function tryGetMethod({ name, source }: ValueInfoFunctionOrClass, modifiers?: Modifiers): MethodDeclaration | undefined { + if (!isValidIdentifier(name)) return undefined; + const fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === SyntaxKind.Constructor)) return undefined; + const sig = getParametersAndReturnType(fnAst); + return sig && createMethod( + /*decorators*/ undefined, + modifiers, + /*asteriskToken*/ undefined, + name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, + sig.parameters, + sig.returnType, + /*body*/ undefined); + } + + function toType(info: ValueInfo): TypeNode { + switch (info.kind) { + case ValueKind.Const: + return createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case ValueKind.Array: + return createArrayTypeNode(toType(info.inner)); + case ValueKind.FunctionOrClass: + return createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case ValueKind.Object: + return createTypeLiteralNode(info.members.map(m => createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined))); + default: + return Debug.assertNever(info); + } + } + + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst: FunctionOrConstructorNode): ReadonlyArray { + const members: PropertyDeclaration[] = []; + forEachOwnNodeOfFunction(fnAst, node => { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + isPropertyAccessExpression(node.left) && node.left.expression.kind === SyntaxKind.ThisKeyword) { + const name = node.left.name.text; + if (!isJsPrivate(name)) members.push(createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + + interface ParametersAndReturnType { readonly parameters: ReadonlyArray; readonly returnType: TypeNode; } + function getParametersAndReturnType(fnAst: FunctionOrConstructor): ParametersAndReturnType { + if (typeof fnAst === "number") { + return { parameters: fill(fnAst, i => makeParameter(`p${i}`, anyType())), returnType: anyType() }; + } + let usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, node => { + usedArguments = usedArguments || isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || isReturnStatement(node) && !!node.expression && node.expression.kind !== SyntaxKind.VoidExpression; + }); + const parameters = [ + ...fnAst.parameters.map(p => makeParameter(`${p.name.getText()}`, inferParameterType(fnAst, p))), + ...(usedArguments ? [makeRestParameter()] : emptyArray), + ]; + return { parameters, returnType: hasReturn ? anyType() : createKeywordTypeNode(SyntaxKind.VoidKeyword) }; + } + function makeParameter(name: string, type: TypeNode): ParameterDeclaration { + return createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter(): ParameterDeclaration { + return createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, createToken(SyntaxKind.DotDotDotToken), "args", /*questionToken*/ undefined, createArrayTypeNode(anyType())); + } + + type FunctionOrConstructorNode = FunctionExpression | ArrowFunction | ConstructorDeclaration | MethodDeclaration; + type FunctionOrConstructor = FunctionOrConstructorNode | number; // number is for native function + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source: string | number): FunctionOrConstructor | undefined { + if (typeof source === "number") return source; + const classOrFunction = tryCast(parseExpression(source), (node): node is FunctionExpression | ArrowFunction | ClassExpression => isFunctionExpression(node) || isArrowFunction(node) || isClassExpression(node)); + return classOrFunction + ? isClassExpression(classOrFunction) ? find(classOrFunction.members, isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : cast(first(cast(parseExpression(`{ ${source} }`), isObjectLiteralExpression).properties), isMethodDeclaration); + } + + function parseExpression(expr: string): Expression { + const text = `const _ = ${expr}`; + const srcFile = createSourceFile("test.ts", text, ScriptTarget.Latest, /*setParentNodes*/ true); + return first(cast(first(srcFile.statements), isVariableStatement).declarationList.declarations).initializer!; + } + + function inferParameterType(_fn: FunctionOrConstructor, _param: ParameterDeclaration): TypeNode { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst: FunctionOrConstructorNode, cb: (node: Node) => void) { + fnAst.body!.forEachChild(function recur(node) { + cb(node); + if (!isFunctionLike(node)) node.forEachChild(recur); + }); + } + + function isValidIdentifier(name: string): boolean { + const keyword = stringToToken(name); + return !(keyword && isNonContextualKeyword(keyword)) && isIdentifierText(name, ScriptTarget.ESNext); + } + + type Modifiers = ReadonlyArray | undefined; + + function addComment(node: T, comment: string | undefined): T { + if (comment !== undefined) addSyntheticLeadingComment(node, SyntaxKind.SingleLineCommentTrivia, comment); + return node; + } + + function anyType(): KeywordTypeNode { + return createKeywordTypeNode(SyntaxKind.AnyKeyword); + } + + function createNamespace(modifiers: Modifiers, name: string, statements: ReadonlyArray): NamespaceDeclaration { + return createModuleDeclaration(/*decorators*/ undefined, modifiers, createIdentifier(name), createModuleBlock(statements), NodeFlags.Namespace) as NamespaceDeclaration; + } +} diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 963d1cd64f2..2f6d68c52f4 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -185,20 +185,20 @@ namespace ts.codefix { const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && defaultInfo.name === symbolName && skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { - result.push({ moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol) }); + result.push({ moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); } for (const exported of checker.getExportsOfModule(moduleSymbol)) { if (exported.name === symbolName && skipAlias(exported, checker) === exportedSymbol) { - result.push({ moduleSymbol, importKind: ImportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + result.push({ moduleSymbol, importKind: ImportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s: Symbol): boolean { - return !(s.flags & SymbolFlags.Value); + function isTypeOnlySymbol(s: Symbol, checker: TypeChecker): boolean { + return !(skipAlias(s, checker).flags & SymbolFlags.Value); } function getFixForImport( @@ -267,7 +267,7 @@ namespace ts.codefix { function getExistingImportDeclarations({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }: SymbolExportInfo, checker: TypeChecker, sourceFile: SourceFile): ReadonlyArray { // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && isSourceFileJavaScript(sourceFile) ? emptyArray : mapDefined(sourceFile.imports, moduleSpecifier => { + return exportedSymbolIsTypeOnly && isSourceFileJS(sourceFile) ? emptyArray : mapDefined(sourceFile.imports, moduleSpecifier => { const i = importFromModuleSpecifier(moduleSpecifier); return (i.kind === SyntaxKind.ImportDeclaration || i.kind === SyntaxKind.ImportEqualsDeclaration) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind } : undefined; @@ -282,7 +282,7 @@ namespace ts.codefix { host: LanguageServiceHost, preferences: UserPreferences, ): ReadonlyArray { - const isJs = isSourceFileJavaScript(sourceFile); + const isJs = isSourceFileJS(sourceFile); const choicesForEachExportingModule = flatMap(moduleSymbols, ({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }) => moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) .map((moduleSpecifier): FixAddNewImport | FixUseImportType => @@ -398,7 +398,7 @@ namespace ts.codefix { // Maps symbol id to info for modules providing that symbol (original export + re-exports). const originalSymbolToExportInfos = createMultiMap(); function addSymbol(moduleSymbol: Symbol, exportedSymbol: Symbol, importKind: ImportKind): void { - originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol, importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol, importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), moduleSymbol => { cancellationToken.throwIfCancellationRequested(); @@ -424,7 +424,7 @@ namespace ts.codefix { if (!exported) return undefined; const { symbol, kind } = exported; const info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); - return info && { symbol, symbolForMeaning: info.symbolForMeaning, name: info.name, kind }; + return info && { symbol, kind, ...info }; } function getDefaultLikeExportWorker(moduleSymbol: Symbol, checker: TypeChecker): { readonly symbol: Symbol, readonly kind: ImportKind.Default | ImportKind.Equals } | undefined { diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 17b3469f0bf..62f73df9f80 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -25,24 +25,21 @@ namespace ts.codefix { registerCodeFix({ errorCodes, getCodeActions(context) { - const { sourceFile, program, span: { start }, errorCode, cancellationToken } = context; - if (isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } + const { sourceFile, program, span: { start }, errorCode, cancellationToken, host } = context; const token = getTokenAtPosition(sourceFile, start); let declaration!: Declaration | undefined; - const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ returnTrue); }); + const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host); }); const name = declaration && getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions(context) { - const { sourceFile, program, cancellationToken } = context; + const { sourceFile, program, cancellationToken, host } = context; const markSeen = nodeSeenTracker(); return codeFixAll(context, errorCodes, (changes, err) => { - doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); @@ -50,7 +47,7 @@ namespace ts.codefix { function getDiagnostic(errorCode: number, token: Node): DiagnosticMessage { switch (errorCode) { case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return isSetAccessor(getContainingFunction(token)!) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + return isSetAccessorDeclaration(getContainingFunction(token)!) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return Diagnostics.Infer_parameter_types_from_usage; default: @@ -58,8 +55,8 @@ namespace ts.codefix { } } - function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker): Declaration | undefined { - if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken) { + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost): Declaration | undefined { + if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken && token.kind !== SyntaxKind.ThisKeyword) { return undefined; } @@ -69,7 +66,15 @@ namespace ts.codefix { case Diagnostics.Member_0_implicitly_has_an_1_type.code: case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((isVariableDeclaration(parent) && markSeen(parent)) || isPropertyDeclaration(parent) || isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (isPropertyAccessExpression(parent)) { + const type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + const typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + changes.tryInsertJSDocType(sourceFile, parent, typeNode); + } return parent; } return undefined; @@ -77,7 +82,7 @@ namespace ts.codefix { case Diagnostics.Variable_0_implicitly_has_an_1_type.code: { const symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -92,15 +97,15 @@ namespace ts.codefix { switch (errorCode) { // Parameter declarations case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { const param = cast(parent, isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); return param; } return undefined; @@ -108,16 +113,16 @@ namespace ts.codefix { // Get Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (isGetAccessor(containingFunction) && isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + if (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; // Set Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -127,9 +132,9 @@ namespace ts.codefix { } } - function annotateVariableDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, program: Program, cancellationToken: CancellationToken): void { + function annotateVariableDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { if (isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } @@ -145,40 +150,67 @@ namespace ts.codefix { return false; } - function annotateParameters(changes: textChanges.ChangeTracker, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): void { + function annotateParameters(changes: textChanges.ChangeTracker, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { if (!isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } - const types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(p => isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; - } + const parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(p => ({ + declaration: p, + type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + })); + Debug.assert(containingFunction.parameters.length === parameterInferences.length); - zipWith(containingFunction.parameters, types, (parameter, type) => { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + if (isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + for (const { declaration, type } of parameterInferences) { + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } - function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, cancellationToken: CancellationToken): void { + function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { const param = firstOrUndefined(setAccessorDeclaration.parameters); if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { const type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + if (isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } - function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type | undefined, program: Program): void { - const typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type | undefined, program: Program, host: LanguageServiceHost): void { + const typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (isInJSFile(sourceFile) && declaration.kind !== SyntaxKind.PropertySignature) { + changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, checker: TypeChecker): TypeNode | undefined { + function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterInferences: ParameterInference[], program: Program, host: LanguageServiceHost): void { + const result = mapDefined(parameterInferences, inference => { + const param = inference.declaration; + const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + return typeNode && !param.initializer && !getJSDocType(param) ? { ...inference, typeNode } : undefined; + }); + changes.tryInsertJSDocParameters(sourceFile, result); + } + + function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined { + const checker = program.getTypeChecker(); let typeIsAccessible = true; const notAccessible = () => { typeIsAccessible = false; }; const res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -189,6 +221,14 @@ namespace ts.codefix { reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } @@ -196,14 +236,14 @@ namespace ts.codefix { function getReferences(token: PropertyName | Token, program: Program, cancellationToken: CancellationToken): ReadonlyArray { // Position shouldn't matter since token is not a SourceFile. return mapDefined(FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), entry => - entry.type === "node" ? tryCast(entry.node, isIdentifier) : undefined); + entry.kind !== FindAllReferences.EntryKind.Span ? tryCast(entry.node, isIdentifier) : undefined); } function inferTypeForVariableFromUsage(token: Identifier, program: Program, cancellationToken: CancellationToken): Type | undefined { return InferFromReference.inferTypeFromReferences(getReferences(token, program, cancellationToken), program.getTypeChecker(), cancellationToken); } - function inferTypeForParametersFromUsage(containingFunction: FunctionLikeDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): (Type | undefined)[] | undefined { + function inferTypeForParametersFromUsage(containingFunction: FunctionLikeDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { switch (containingFunction.kind) { case SyntaxKind.Constructor: case SyntaxKind.FunctionExpression: @@ -219,6 +259,13 @@ namespace ts.codefix { } } + interface ParameterInference { + declaration: ParameterDeclaration; + type?: Type; + typeNode?: TypeNode; + isOptional?: boolean; + } + namespace InferFromReference { interface CallContext { argumentTypes: Type[]; @@ -246,7 +293,7 @@ namespace ts.codefix { return getTypeFromUsageContext(usageContext, checker); } - export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLikeDeclaration, checker: TypeChecker, cancellationToken: CancellationToken): (Type | undefined)[] | undefined { + export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLikeDeclaration, checker: TypeChecker, cancellationToken: CancellationToken): ParameterInference[] | undefined { if (references.length === 0) { return undefined; } @@ -265,8 +312,10 @@ namespace ts.codefix { return callContexts && declaration.parameters.map((parameter, parameterIndex) => { const types: Type[] = []; const isRest = isRestParameter(parameter); + let isOptional = false; for (const callContext of callContexts) { if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = isInJSFile(declaration); continue; } @@ -280,10 +329,14 @@ namespace ts.codefix { } } if (!types.length) { - return undefined; + return { declaration: parameter }; } const type = checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype)); - return isRest ? checker.createArrayType(type) : type; + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } diff --git a/src/services/completions.ts b/src/services/completions.ts index 16e48dc56b6..e2c7be0298a 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -43,7 +43,7 @@ namespace ts.Completions { } const contextToken = findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) return undefined; + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; if (isInString(sourceFile, position, contextToken)) { return !contextToken || !isStringLiteralLike(contextToken) @@ -134,7 +134,7 @@ namespace ts.Completions { if (isUncheckedFile(sourceFile, compilerOptions)) { const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target!, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === KeywordCompletionFilters.None) { @@ -161,7 +161,7 @@ namespace ts.Completions { } function isUncheckedFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean { - return isSourceFileJavaScript(sourceFile) && !isCheckJsEnabledForFile(sourceFile, compilerOptions); + return isSourceFileJS(sourceFile) && !isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind: CompletionKind): boolean { @@ -175,7 +175,7 @@ namespace ts.Completions { } } - function getJavaScriptCompletionEntries( + function getJSCompletionEntries( sourceFile: SourceFile, position: number, uniqueNames: Map, @@ -390,11 +390,12 @@ namespace ts.Completions { } type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: ReadonlyArray } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost): StringLiteralCompletion | undefined { - switch (node.parent.kind) { + const { parent } = node; + switch (parent.kind) { case SyntaxKind.LiteralType: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case SyntaxKind.TypeReference: - return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent as LiteralTypeNode)), isNewIdentifier: false }; + return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent as LiteralTypeNode)), isNewIdentifier: false }; case SyntaxKind.IndexedAccessType: // Get all apparent property names // i.e. interface Foo { @@ -402,17 +403,21 @@ namespace ts.Completions { // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((node.parent.parent as IndexedAccessTypeNode).objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((parent.parent as IndexedAccessTypeNode).objectType)); case SyntaxKind.ImportType: return { kind: StringLiteralCompletionKind.Paths, paths: PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case SyntaxKind.UnionType: - return isTypeReferenceNode(node.parent.parent.parent) ? { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent as UnionTypeNode)), isNewIdentifier: false } : undefined; + case SyntaxKind.UnionType: { + if (!isTypeReferenceNode(parent.parent.parent)) return undefined; + const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(parent.parent as UnionTypeNode, parent as LiteralTypeNode); + const types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent as UnionTypeNode)).filter(t => !contains(alreadyUsedTypes, t.value)); + return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier: false }; + } default: return undefined; } case SyntaxKind.PropertyAssignment: - if (isObjectLiteralExpression(node.parent.parent) && (node.parent).name === node) { + if (isObjectLiteralExpression(parent.parent) && (parent).name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -425,12 +430,12 @@ namespace ts.Completions { // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case SyntaxKind.ElementAccessExpression: { - const { expression, argumentExpression } = node.parent as ElementAccessExpression; + const { expression, argumentExpression } = parent as ElementAccessExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -445,7 +450,7 @@ namespace ts.Completions { case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: - if (!isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(node.parent)) { + if (!isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(parent)) { const argumentInfo = SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -476,6 +481,11 @@ namespace ts.Completions { } } + function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current: LiteralTypeNode): ReadonlyArray { + return mapDefined(union.types, type => + type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined); + } + function getStringLiteralCompletionsFromSignature(argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker): StringLiteralCompletionsFromTypes { let isNewIdentifier = false; @@ -1190,9 +1200,9 @@ namespace ts.Completions { function tryGetJsxCompletionSymbols(): GlobalsSearch { const jsxContainer = tryGetContainingJsxElement(contextToken); // Cursor is inside a JSX self-closing element or opening element - const attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + const attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); if (!attrsType) return GlobalsSearch.Continue; - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer!.attributes.properties); + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer!.attributes, typeChecker), jsxContainer!.attributes.properties); completionKind = CompletionKind.MemberLike; isNewIdentifierLocation = false; return GlobalsSearch.Success; @@ -1268,10 +1278,10 @@ namespace ts.Completions { if (sourceFile.externalModuleIndicator) return true; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (programContainsEs6Modules(program)) return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (programContainsEs6Modules(program)) return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -1387,7 +1397,7 @@ namespace ts.Completions { if (resolvedModuleSymbol !== moduleSymbol && // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - resolvedModuleSymbol.declarations.some(d => !!d.getSourceFile().externalModuleIndicator)) { + some(resolvedModuleSymbol.declarations, d => !!d.getSourceFile().externalModuleIndicator)) { symbols.push(resolvedModuleSymbol); symbolToOriginInfoMap[getSymbolId(resolvedModuleSymbol)] = { kind: SymbolOriginInfoKind.Export, moduleSymbol, isDefaultExport: false }; } @@ -1703,6 +1713,9 @@ namespace ts.Completions { break; case SyntaxKind.AsteriskToken: return isMethodDeclaration(parent) ? tryCast(parent.parent, isObjectLiteralExpression) : undefined; + case SyntaxKind.Identifier: + return (contextToken as Identifier).text === "async" && isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } @@ -1918,7 +1931,6 @@ namespace ts.Completions { // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { case SyntaxKind.AbstractKeyword: - case SyntaxKind.AsyncKeyword: case SyntaxKind.ClassKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DeclareKeyword: @@ -1933,6 +1945,8 @@ namespace ts.Completions { case SyntaxKind.VarKeyword: case SyntaxKind.YieldKeyword: return true; + case SyntaxKind.AsyncKeyword: + return isPropertyDeclaration(contextToken.parent); } return isDeclarationName(contextToken) @@ -2197,7 +2211,7 @@ namespace ts.Completions { return jsdoc && jsdoc.tags && (rangeContainsPosition(jsdoc, position) ? findLast(jsdoc.tags, tag => tag.pos < position) : undefined); } - function getPropertiesForObjectExpression(contextualType: Type, obj: ObjectLiteralExpression, checker: TypeChecker): Symbol[] { + function getPropertiesForObjectExpression(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes, checker: TypeChecker): Symbol[] { return contextualType.isUnion() ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(memberType => // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. @@ -2262,7 +2276,7 @@ namespace ts.Completions { return !!type.getStringIndexType() || !!type.getNumberIndexType(); } - function isValidTrigger(sourceFile: SourceFile, triggerCharacter: CompletionsTriggerCharacter, contextToken: Node, position: number): boolean { + function isValidTrigger(sourceFile: SourceFile, triggerCharacter: CompletionsTriggerCharacter, contextToken: Node | undefined, position: number): boolean { switch (triggerCharacter) { case ".": case "@": @@ -2271,14 +2285,14 @@ namespace ts.Completions { case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === SyntaxKind.LessThanToken && (!isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === SyntaxKind.LessThanToken && (!isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return isStringLiteralLike(contextToken) + return !!contextToken && (isStringLiteralLike(contextToken) ? !!tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === SyntaxKind.SlashToken && isJsxClosingElement(contextToken.parent); + : contextToken.kind === SyntaxKind.SlashToken && isJsxClosingElement(contextToken.parent)); default: return Debug.assertNever(triggerCharacter); } diff --git a/src/services/documentRegistry.ts b/src/services/documentRegistry.ts index 7a21cebb4f3..5720c69be68 100644 --- a/src/services/documentRegistry.ts +++ b/src/services/documentRegistry.ts @@ -121,10 +121,6 @@ namespace ts { const buckets = createMap>(); const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey { - return `_${settings.target}|${settings.module}|${settings.noResolve}|${settings.jsx}|${settings.allowJs}|${settings.baseUrl}|${JSON.stringify(settings.typeRoots)}|${JSON.stringify(settings.rootDirs)}|${JSON.stringify(settings.paths)}`; - } - function getBucketForCompilationSettings(key: DocumentRegistryBucketKey, createIfMissing: boolean): Map { let bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -273,4 +269,8 @@ namespace ts { getKeyForCompilationSettings }; } + + function getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey { + return sourceFileAffectingCompilerOptions.map(option => getCompilerOptionValue(settings, option)).join("|") as DocumentRegistryBucketKey; + } } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index b857a05dffb..9fde734049c 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -13,19 +13,20 @@ namespace ts.FindAllReferences { | { readonly type: DefinitionKind.This; readonly node: Node } | { readonly type: DefinitionKind.String; readonly node: StringLiteral }; + export const enum EntryKind { Span, Node, StringLiteral, SearchedLocalFoundProperty, SearchedPropertyFoundLocal } + export type NodeEntryKind = EntryKind.Node | EntryKind.StringLiteral | EntryKind.SearchedLocalFoundProperty | EntryKind.SearchedPropertyFoundLocal; export type Entry = NodeEntry | SpanEntry; export interface NodeEntry { - type: "node"; - node: Node; - isInString?: true; + readonly kind: NodeEntryKind; + readonly node: Node; } export interface SpanEntry { - type: "span"; - fileName: string; - textSpan: TextSpan; + readonly kind: EntryKind.Span; + readonly fileName: string; + readonly textSpan: TextSpan; } - export function nodeEntry(node: Node, isInString?: true): NodeEntry { - return { type: "node", node: (node as NamedDeclaration).name || node, isInString }; + export function nodeEntry(node: Node, kind: NodeEntryKind = EntryKind.Node): NodeEntry { + return { kind, node: (node as NamedDeclaration).name || node }; } export interface Options { @@ -33,7 +34,7 @@ namespace ts.FindAllReferences { readonly findInComments?: boolean; /** * True if we are renaming the symbol. - * If so, we will find fewer references -- if it is referenced by several different names, we sill only find references for the original name. + * If so, we will find fewer references -- if it is referenced by several different names, we still only find references for the original name. */ readonly isForRename?: boolean; /** True if we are searching for implementations. We will have a different method of adding references if so. */ @@ -84,10 +85,15 @@ namespace ts.FindAllReferences { } } - export function findReferencedEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number, options: Options | undefined): ReferenceEntry[] | undefined { - return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + export function findReferenceOrRenameEntries( + program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number, options: Options | undefined, + convertEntry: ToReferenceOrRenameEntry, + ): T[] | undefined { + return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), entry => convertEntry(entry, node)); } + export type ToReferenceOrRenameEntry = (entry: Entry, originalNode: Node) => T; + export function getReferenceEntriesForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlyMap = arrayToSet(sourceFiles, f => f.fileName)): Entry[] | undefined { return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); } @@ -143,26 +149,64 @@ namespace ts.FindAllReferences { return { displayParts, kind: symbolKind }; } - function toReferenceEntry(entry: Entry): ReferenceEntry { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; - } + export function toRenameLocation(entry: Entry, originalNode: Node): RenameLocation { + return { ...entryToDocumentSpan(entry), ...getPrefixAndSuffixText(entry, originalNode) }; + } - const { node, isInString } = entry; - const sourceFile = node.getSourceFile(); + export function toReferenceEntry(entry: Entry): ReferenceEntry { + const { textSpan, fileName } = entryToDocumentSpan(entry); + if (entry.kind === EntryKind.Span) { + return { textSpan, fileName, isWriteAccess: false, isDefinition: false }; + } + const { kind, node } = entry; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan, + fileName, isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === SyntaxKind.DefaultKeyword || !!getDeclarationFromName(node) || isLiteralComputedPropertyDeclarationName(node), - isInString, + isInString: kind === EntryKind.StringLiteral ? true : undefined, }; } + function entryToDocumentSpan(entry: Entry): DocumentSpan { + if (entry.kind === EntryKind.Span) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + const sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + + function getPrefixAndSuffixText(entry: Entry, originalNode: Node): { readonly prefixText?: string, readonly suffixText?: string } { + if (entry.kind !== EntryKind.Span && isIdentifier(originalNode)) { + const { node, kind } = entry; + const name = originalNode.text; + const isShorthandAssignment = isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || isObjectBindingElementWithoutPropertyName(node.parent)) { + if (kind === EntryKind.SearchedLocalFoundProperty) { + return { prefixText: name + ": " }; + } + else if (kind === EntryKind.SearchedPropertyFoundLocal) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: name + ": " }; + } + } + } + + return emptyOptions; + } + function toImplementationLocation(entry: Entry, checker: TypeChecker): ImplementationLocation { - if (entry.type === "node") { + if (entry.kind !== EntryKind.Span) { const { node } = entry; const sourceFile = node.getSourceFile(); return { textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName, ...implementationKindDisplayParts(node, checker) }; @@ -196,18 +240,18 @@ namespace ts.FindAllReferences { } export function toHighlightSpan(entry: Entry): { fileName: string, span: HighlightSpan } { - if (entry.type === "span") { + if (entry.kind === EntryKind.Span) { const { fileName, textSpan } = entry; return { fileName, span: { textSpan, kind: HighlightSpanKind.reference } }; } - const { node, isInString } = entry; + const { node, kind } = entry; const sourceFile = node.getSourceFile(); const writeAccess = isWriteAccessForReference(node); const span: HighlightSpan = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference, - isInString + isInString: kind === EntryKind.StringLiteral ? true : undefined, }; return { fileName: sourceFile.fileName, span }; } @@ -348,11 +392,11 @@ namespace ts.FindAllReferences.Core { } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return nodeEntry(reference.literal); } else { return { - type: "span", + kind: EntryKind.Span, fileName: reference.referencingFile.fileName, textSpan: createTextSpanFromRange(reference.ref), }; @@ -366,7 +410,7 @@ namespace ts.FindAllReferences.Core { break; case SyntaxKind.ModuleDeclaration: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: (decl as ModuleDeclaration).name }); + references.push(nodeEntry((decl as ModuleDeclaration).name)); } break; default: @@ -422,7 +466,7 @@ namespace ts.FindAllReferences.Core { searchForImportsOfExport(node, symbol, { exportingModuleSymbol: Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: ExportKind.Default }, state); } else { - const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!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). @@ -581,21 +625,21 @@ namespace ts.FindAllReferences.Core { * Callback to add references for a particular searched symbol. * This initializes a reference group, so only call this if you will add at least one reference. */ - referenceAdder(searchSymbol: Symbol): (node: Node) => void { + referenceAdder(searchSymbol: Symbol): (node: Node, kind?: NodeEntryKind) => void { const symbolId = getSymbolId(searchSymbol); let references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; this.result.push({ definition: { type: DefinitionKind.Symbol, symbol: searchSymbol }, references }); } - return node => references.push(nodeEntry(node)); + return (node, kind) => references.push(nodeEntry(node, kind)); } /** Add a reference with no associated definition. */ addStringOrCommentReference(fileName: string, textSpan: TextSpan): void { this.result.push({ definition: undefined, - references: [{ type: "span", fileName, textSpan }] + references: [{ kind: EntryKind.Span, fileName, textSpan }] }); } @@ -707,21 +751,6 @@ namespace ts.FindAllReferences.Core { : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol: Symbol): BindingElement & { name: Identifier } | undefined { - const bindingElement = getDeclarationOfKind(symbol, SyntaxKind.BindingElement); - if (bindingElement && - bindingElement.parent.kind === SyntaxKind.ObjectBindingPattern && - isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement as BindingElement & { name: Identifier }; - } - } - - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol, checker: TypeChecker): Symbol | undefined { - const bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && getPropertySymbolFromBindingElement(checker, bindingElement); - } - /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -754,7 +783,7 @@ namespace ts.FindAllReferences.Core { // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(isObjectBindingElementWithoutPropertyName)) { return undefined; } @@ -1099,13 +1128,14 @@ namespace ts.FindAllReferences.Core { } } - function addReference(referenceLocation: Node, relatedSymbol: Symbol, state: State): void { - const addRef = state.referenceAdder(relatedSymbol); + function addReference(referenceLocation: Node, relatedSymbol: Symbol | RelatedSymbol, state: State): void { + const { kind, symbol } = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }; + const addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } @@ -1428,7 +1458,7 @@ namespace ts.FindAllReferences.Core { const references = flatMap(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), ref => - isStringLiteral(ref) && ref.text === node.text ? nodeEntry(ref, /*isInString*/ true) : undefined); + isStringLiteral(ref) && ref.text === node.text ? nodeEntry(ref, EntryKind.StringLiteral) : undefined); }); return [{ @@ -1439,35 +1469,21 @@ namespace ts.FindAllReferences.Core { // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol: Symbol, location: Node, checker: TypeChecker, implementations: boolean): Symbol[] { + function populateSearchSymbolSet(symbol: Symbol, location: Node, checker: TypeChecker, isForRename: boolean, implementations: boolean): Symbol[] { const result: Symbol[] = []; - forEachRelatedSymbol(symbol, location, checker, + forEachRelatedSymbol(symbol, location, checker, isForRename, (sym, root, base) => { result.push(base || root || sym); }, /*allowBaseTypes*/ () => !implementations); return result; } function forEachRelatedSymbol( - symbol: Symbol, location: Node, checker: TypeChecker, - cbSymbol: (symbol: Symbol, rootSymbol?: Symbol, baseSymbol?: Symbol) => T | undefined, + symbol: Symbol, location: Node, checker: TypeChecker, isForRenamePopulateSearchSymbolSet: boolean, + cbSymbol: (symbol: Symbol, rootSymbol?: Symbol, baseSymbol?: Symbol, kind?: NodeEntryKind) => T | undefined, allowBaseTypes: (rootSymbol: Symbol) => boolean, ): T | undefined { const containingObjectLiteralElement = getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - const contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - const res = contextualType && firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res) return res; - - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - const propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - const res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) return res1; - /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -1479,8 +1495,29 @@ namespace ts.FindAllReferences.Core { * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - const shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - const res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + const shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, EntryKind.SearchedLocalFoundProperty); + } + + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + const contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + const res = contextualType && firstDefined( + getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), + sym => fromRoot(sym, EntryKind.SearchedPropertyFoundLocal)); + if (res) return res; + + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + const propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + const res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, EntryKind.SearchedPropertyFoundLocal); + if (res1) return res1; + + const res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, EntryKind.SearchedLocalFoundProperty); if (res2) return res2; } @@ -1494,12 +1531,14 @@ namespace ts.FindAllReferences.Core { return fromRoot(symbol.flags & SymbolFlags.FunctionScopedVariable ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + const bindingElementPropertySymbol = isObjectBindingElementWithoutPropertyName(location.parent) ? getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, EntryKind.SearchedPropertyFoundLocal); + } - function fromRoot(sym: Symbol): T | undefined { + function fromRoot(sym: Symbol, kind?: NodeEntryKind): T | undefined { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -1507,20 +1546,24 @@ namespace ts.FindAllReferences.Core { // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return firstDefined(checker.getRootSymbols(sym), rootSymbol => - cbSymbol(sym, rootSymbol) + cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface) && allowBaseTypes(rootSymbol) - ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, base => cbSymbol(sym, rootSymbol, base)) + ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, base => cbSymbol(sym, rootSymbol, base, kind)) : undefined)); } } - function getRelatedSymbol(search: Search, referenceSymbol: Symbol, referenceLocation: Node, state: State): Symbol | undefined { + interface RelatedSymbol { + readonly symbol: Symbol; + readonly kind: NodeEntryKind | undefined; + } + function getRelatedSymbol(search: Search, referenceSymbol: Symbol, referenceLocation: Node, state: State): RelatedSymbol | undefined { const { checker } = state; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, - (sym, rootSymbol, baseSymbol) => search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, + (sym, rootSymbol, baseSymbol, kind): RelatedSymbol | undefined => search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(getCheckFlags(sym) & CheckFlags.Synthetic) ? rootSymbol : sym + ? { symbol: rootSymbol && !(getCheckFlags(sym) & CheckFlags.Synthetic) ? rootSymbol : sym, kind } : undefined, /*allowBaseTypes*/ rootSymbol => !(search.parents && !search.parents.some(parent => explicitlyInheritsFrom(rootSymbol.parent!, parent, state.inheritsFromCache, checker)))); diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index c1de1574e88..0ed6e84e2c3 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -753,17 +753,17 @@ namespace ts.formatting { const listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== SyntaxKind.Unknown && formattingScanner.isOnToken()) { - let tokenInfo = formattingScanner.readTokenInfo(parent); + let tokenInfo: TokenInfo | undefined = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === SyntaxKind.CommaToken && isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } diff --git a/src/services/getEditsForFileRename.ts b/src/services/getEditsForFileRename.ts index 07c3eb7ad22..5872ade5652 100644 --- a/src/services/getEditsForFileRename.ts +++ b/src/services/getEditsForFileRename.ts @@ -72,7 +72,7 @@ namespace ts { case "compilerOptions": forEachProperty(property.initializer, (property, propertyName) => { const option = getOptionFromName(propertyName); - if (option && (option.isFilePath || option.type === "list" && (option as CommandLineOptionOfListType).element.isFilePath)) { + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { updatePaths(property); } else if (propertyName === "paths") { @@ -196,15 +196,23 @@ namespace ts { } function getSourceFileToImportFromResolved(resolved: ResolvedModuleWithFailedLookupLocations | undefined, oldToNew: PathUpdater, host: LanguageServiceHost): ToImport | undefined { - return resolved && ( - (resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || firstDefined(resolved.failedLookupLocations, getIfExists)); + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); - function getIfExists(oldLocation: string): ToImport | undefined { - const newLocation = oldToNew(oldLocation); + function tryEach(cb: (oldFileName: string) => ToImport | undefined): ToImport | undefined { + return resolved && ( + (resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || firstDefined(resolved.failedLookupLocations, cb)); + } - return host.fileExists!(oldLocation) || newLocation !== undefined && host.fileExists!(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + function tryGetNewFile(oldFileName: string): ToImport | undefined { + const newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists!(newFileName) ? { newFileName, updated: true } : undefined; // TODO: GH#18217 + } + + function tryGetOldFile(oldFileName: string): ToImport | undefined { + const newFileName = oldToNew(oldFileName); + return host.fileExists!(oldFileName) ? newFileName !== undefined ? { newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index 77b3c02c80b..9872b378403 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -385,7 +385,7 @@ namespace ts.FindAllReferences { } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ - function forEachPossibleImportOrExportStatement(sourceFileLike: SourceFileLike, action: (statement: Statement) => T): T | undefined { + function forEachPossibleImportOrExportStatement(sourceFileLike: SourceFileLike, action: (statement: Statement) => T) { return forEach(sourceFileLike.kind === SyntaxKind.SourceFile ? sourceFileLike.statements : sourceFileLike.body!.statements, statement => // TODO: GH#18217 action(statement) || (isAmbientModuleDeclaration(statement) && forEach(statement.body && statement.body.statements, action))); } @@ -502,11 +502,11 @@ namespace ts.FindAllReferences { function getSpecialPropertyExport(node: BinaryExpression, useLhsSymbol: boolean): ExportedSymbol | undefined { let kind: ExportKind; - switch (getSpecialPropertyAssignmentKind(node)) { - case SpecialPropertyAssignmentKind.ExportsProperty: + switch (getAssignmentDeclarationKind(node)) { + case AssignmentDeclarationKind.ExportsProperty: kind = ExportKind.Named; break; - case SpecialPropertyAssignmentKind.ModuleExports: + case AssignmentDeclarationKind.ModuleExports: kind = ExportKind.ExportEquals; break; default: diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index d9fa8446b13..8016b0e9ff6 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -208,7 +208,7 @@ namespace ts.JsDoc { kindModifiers: "", displayParts: [textPart(name)], documentation: emptyArray, - tags: emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -242,7 +242,7 @@ namespace ts.JsDoc { kindModifiers: "", displayParts: [textPart(name)], documentation: emptyArray, - tags: emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -312,7 +312,7 @@ namespace ts.JsDoc { const preamble = "/**" + newLine + indentationStr + " * "; const result = preamble + newLine + - parameterDocComments(parameters, hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); @@ -383,7 +383,7 @@ namespace ts.JsDoc { case SyntaxKind.BinaryExpression: { const be = commentOwner as BinaryExpression; - if (getSpecialPropertyAssignmentKind(be) === SpecialPropertyAssignmentKind.None) { + if (getAssignmentDeclarationKind(be) === AssignmentDeclarationKind.None) { return "quit"; } const parameters = isFunctionLike(be.right) ? be.right.parameters : emptyArray; diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 504311a4a2d..03d2aec13c5 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -270,17 +270,17 @@ namespace ts.NavigationBar { break; case SyntaxKind.BinaryExpression: { - const special = getSpecialPropertyAssignmentKind(node as BinaryExpression); + const special = getAssignmentDeclarationKind(node as BinaryExpression); switch (special) { - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ModuleExports: - case SpecialPropertyAssignmentKind.PrototypeProperty: - case SpecialPropertyAssignmentKind.Prototype: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.ModuleExports: + case AssignmentDeclarationKind.PrototypeProperty: + case AssignmentDeclarationKind.Prototype: addNodeWithRecursiveChild(node, (node as BinaryExpression).right); return; - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.ThisProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.None: break; default: Debug.assertNever(special); @@ -631,28 +631,50 @@ namespace ts.NavigationBar { } function getFunctionOrClassName(node: FunctionExpression | FunctionDeclaration | ArrowFunction | ClassLikeDeclaration): string { + const { parent } = node; if (node.name && getFullWidth(node.name) > 0) { return declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === SyntaxKind.VariableDeclaration) { - return declarationNameToString((node.parent as VariableDeclaration).name); + else if (isVariableDeclaration(parent)) { + return declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === SyntaxKind.BinaryExpression && - (node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { - return nodeText((node.parent as BinaryExpression).left).replace(whiteSpaceRegex, ""); + else if (isBinaryExpression(parent) && parent.operatorToken.kind === SyntaxKind.EqualsToken) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === SyntaxKind.PropertyAssignment && (node.parent as PropertyAssignment).name) { - return nodeText((node.parent as PropertyAssignment).name); + else if (isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (getModifierFlags(node) & ModifierFlags.Default) { return "default"; } + else if (isClassLike(node)) { + return ""; + } + else if (isCallExpression(parent)) { + const name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + const args = mapDefined(parent.arguments, a => isStringLiteral(a) ? a.getText(curSourceFile) : undefined).join(", "); + return `${name}(${args}) callback`; + } + } + return ""; + } + + function getCalledExpressionName(expr: Expression): string | undefined { + if (isIdentifier(expr)) { + return expr.text; + } + else if (isPropertyAccessExpression(expr)) { + const left = getCalledExpressionName(expr.expression); + const right = expr.name.text; + return left === undefined ? right : `${left}.${right}`; + } else { - return isClassLike(node) ? "" : ""; + return undefined; } } diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index 8ab7cc315ad..22cc56903c0 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -151,11 +151,41 @@ namespace ts.Completions.PathCompletions { } } } + + // check for a version redirect + const packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + const packageJson = readJson(packageJsonPath, host as { readFile: (filename: string) => string | undefined }); + const typesVersions = (packageJson as any).typesVersions; + if (typeof typesVersions === "object") { + const versionResult = getPackageJsonTypesVersionsPaths(typesVersions); + const versionPaths = versionResult && versionResult.paths; + const rest = absolutePath.slice(ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result: NameAndKind[], fragment: string, baseDirectory: string, fileExtensions: ReadonlyArray, paths: MapLike, host: LanguageServiceHost) { + for (const path in paths) { + if (!hasProperty(paths, path)) continue; + const patterns = paths[path]; + if (patterns) { + for (const { name, kind } of getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host)) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(entry => entry.name === name)) { + result.push(nameAndKind(name, kind)); + } + } + } + } + } + /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -171,19 +201,10 @@ namespace ts.Completions.PathCompletions { const fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { const projectDir = compilerOptions.project || host.getCurrentDirectory(); - const absolute = isRootedDiskPath(baseUrl) ? baseUrl : combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - - for (const path in paths!) { - const patterns = paths![path]; - if (paths!.hasOwnProperty(path) && patterns) { - for (const { name, kind } of getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host)) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(entry => entry.name === name)) { - result.push(nameAndKind(name, kind)); - } - } - } + const absolute = normalizePath(combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } @@ -329,7 +350,7 @@ namespace ts.Completions.PathCompletions { const seen = createMap(); if (options.types) { for (const typesName of options.types) { - const moduleName = getUnmangledNameForScopedPackage(typesName); + const moduleName = unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -363,7 +384,7 @@ namespace ts.Completions.PathCompletions { for (let typeDirectory of directories) { typeDirectory = normalizePath(typeDirectory); const directoryName = getBaseFileName(typeDirectory); - const moduleName = getUnmangledNameForScopedPackage(directoryName); + const moduleName = unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -390,6 +411,18 @@ namespace ts.Completions.PathCompletions { return paths; } + function findPackageJson(directory: string, host: LanguageServiceHost): string | undefined { + let packageJson: string | undefined; + forEachAncestorDirectory(directory, ancestor => { + if (ancestor === "node_modules") return true; + packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } + function enumerateNodeModulesVisibleToScript(host: LanguageServiceHost, scriptPath: string): ReadonlyArray { if (!host.readFile || !host.fileExists) return emptyArray; diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 93baf2b4209..96b5ba18070 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -719,7 +719,7 @@ namespace ts.refactor.extractSymbol { // Make a unique name for the extracted function const file = scope.getSourceFile(); const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); - const isJS = isInJavaScriptFile(scope); + const isJS = isInJSFile(scope); const functionName = createIdentifier(functionNameText); @@ -1006,7 +1006,7 @@ namespace ts.refactor.extractSymbol { // Make a unique name for the extracted variable const file = scope.getSourceFile(); const localNameText = getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); - const isJS = isInJavaScriptFile(scope); + const isJS = isInJSFile(scope); const variableType = isJS || !checker.isContextSensitive(node) ? undefined @@ -1424,7 +1424,7 @@ namespace ts.refactor.extractSymbol { if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (isClassLike(scope) && isInJavaScriptFile(scope)) { + if (isClassLike(scope) && isInJSFile(scope)) { constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (isArrowFunction(scope) && !isBlock(scope.body)) { diff --git a/src/services/refactors/generateGetAccessorAndSetAccessor.ts b/src/services/refactors/generateGetAccessorAndSetAccessor.ts index e39eb20f8d8..96b8b1e8b06 100644 --- a/src/services/refactors/generateGetAccessorAndSetAccessor.ts +++ b/src/services/refactors/generateGetAccessorAndSetAccessor.ts @@ -41,7 +41,7 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { const fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - const isJS = isSourceFileJavaScript(file); + const isJS = isSourceFileJS(file); const changeTracker = textChanges.ChangeTracker.fromContext(context); const { isStatic, isReadonly, fieldName, accessorName, originalName, type, container, declaration, renameAccessor } = fieldInfo; @@ -226,7 +226,7 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { const { file, program, cancellationToken } = context; const referenceEntries = mapDefined(FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken!), entry => // TODO: GH#18217 - (entry.type === "node" && rangeContainsRange(constructor, entry.node) && isIdentifier(entry.node) && isWriteAccess(entry.node)) ? entry.node : undefined); + (entry.kind !== FindAllReferences.EntryKind.Span && rangeContainsRange(constructor, entry.node) && isIdentifier(entry.node) && isWriteAccess(entry.node)) ? entry.node : undefined); forEach(referenceEntries, entry => { const parent = entry.parent; diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index 9953293e3d1..693cdd9c6cb 100644 --- a/src/services/refactors/moveToNewFile.ts +++ b/src/services/refactors/moveToNewFile.ts @@ -158,7 +158,7 @@ namespace ts.refactor { const shouldMove = (name: Identifier): boolean => { const symbol = isBindingElement(name.parent) - ? getPropertySymbolFromBindingElement(checker, name.parent as BindingElement & { name: Identifier }) + ? getPropertySymbolFromBindingElement(checker, name.parent as ObjectBindingElementWithoutPropertyName) : skipAlias(checker.getSymbolAtLocation(name)!, checker); // TODO: GH#18217 return !!symbol && movedSymbols.has(symbol); }; @@ -657,7 +657,7 @@ namespace ts.refactor { case SyntaxKind.ExpressionStatement: { const { expression } = statement as ExpressionStatement; - return isBinaryExpression(expression) && getSpecialPropertyAssignmentKind(expression) === SpecialPropertyAssignmentKind.ExportsProperty + return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === AssignmentDeclarationKind.ExportsProperty ? cb(statement as TopLevelExpressionStatement) : undefined; } diff --git a/src/services/rename.ts b/src/services/rename.ts index 43f76ff4428..7ba32c91309 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -25,8 +25,9 @@ namespace ts.Rename { return undefined; } - // Can't rename a module name. - if (isStringLiteralLike(node) && tryGetImportFromModuleSpecifier(node)) return undefined; + if (isStringLiteralLike(node) && tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } const kind = SymbolDisplay.getSymbolKind(typeChecker, symbol, node); const specifierName = (isImportOrExportSpecifierName(node) || isStringOrNumericLiteralLike(node) && node.parent.kind === SyntaxKind.ComputedPropertyName) @@ -37,29 +38,44 @@ namespace ts.Rename { return getRenameInfoSuccess(displayName, fullDisplayName, kind, SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } - function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo { + function getRenameInfoForModule(node: StringLiteralLike, sourceFile: SourceFile, moduleSymbol: Symbol): RenameInfo | undefined { + if (!isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + + const moduleSourceFile = find(moduleSymbol.declarations, isSourceFile); + if (!moduleSourceFile) return undefined; + const withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : tryRemoveSuffix(removeFileExtension(moduleSourceFile.fileName), "/index"); + const name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + const kind = withoutIndex === undefined ? ScriptElementKind.moduleElement : ScriptElementKind.directory; + const indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + const triggerSpan = createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); return { canRename: true, + fileToRename: name, + kind, + displayName: name, + fullDisplayName: name, + kindModifiers: ScriptElementKindModifier.none, + triggerSpan, + }; + } + + function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfoSuccess { + return { + canRename: true, + fileToRename: undefined, kind, displayName, - localizedErrorMessage: undefined, fullDisplayName, kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } - function getRenameInfoError(diagnostic: DiagnosticMessage): RenameInfo { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: getLocaleSpecificMessage(diagnostic), - displayName: undefined!, - fullDisplayName: undefined!, - kind: undefined!, - kindModifiers: undefined!, - triggerSpan: undefined! - }; + function getRenameInfoError(diagnostic: DiagnosticMessage): RenameInfoFailure { + return { canRename: false, localizedErrorMessage: getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node: Node, sourceFile: SourceFile) { diff --git a/src/services/services.ts b/src/services/services.ts index dcc321b00d5..9e08f1b14a6 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -541,6 +541,7 @@ namespace ts { public fileName: string; public path: Path; public resolvedPath: Path; + public originalFileName: string; public text: string; public scriptSnapshot: IScriptSnapshot; public lineMap: ReadonlyArray; @@ -760,7 +761,7 @@ namespace ts { break; case SyntaxKind.BinaryExpression: - if (getSpecialPropertyAssignmentKind(node as BinaryExpression) !== SpecialPropertyAssignmentKind.None) { + if (getAssignmentDeclarationKind(node as BinaryExpression) !== AssignmentDeclarationKind.None) { addDeclaration(node as BinaryExpression); } // falls through @@ -1175,9 +1176,10 @@ namespace ts { const rootFileNames = hostCache.getRootFileNames(); const hasInvalidatedResolution: HasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse; + const projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), path => hostCache!.getVersion(path), fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), path => hostCache!.getVersion(path), fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } @@ -1217,6 +1219,10 @@ namespace ts { getDirectories: path => { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory(path, extensions, exclude, include, depth) { + Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory!(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -1240,7 +1246,7 @@ namespace ts { options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences }; program = createProgram(options); @@ -1377,7 +1383,7 @@ namespace ts { // Therefore only get diagnostics for given file. const semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } @@ -1538,20 +1544,20 @@ namespace ts { const node = getTouchingPropertyName(sourceFile, position); if (isIdentifier(node) && isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) { const { openingElement, closingElement } = node.parent.parent; - return [openingElement, closingElement].map((node): RenameLocation => ({ fileName: sourceFile.fileName, textSpan: createTextSpanFromNode(node.tagName, sourceFile) })); + return [openingElement, closingElement].map((node): RenameLocation => + ({ fileName: sourceFile.fileName, textSpan: createTextSpanFromNode(node.tagName, sourceFile) })); } else { - const refs = getReferences(node, position, { findInStrings, findInComments, isForRename: true }); - return refs && refs.map(({ fileName, textSpan }): RenameLocation => ({ fileName, textSpan })); + return getReferencesWorker(node, position, { findInStrings, findInComments, isForRename: true }, FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined { synchronizeHostData(); - return getReferences(getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, FindAllReferences.toReferenceEntry); } - function getReferences(node: Node, position: number, options?: FindAllReferences.Options): ReferenceEntry[] | undefined { + function getReferencesWorker(node: Node, position: number, options: FindAllReferences.Options, cb: FindAllReferences.ToReferenceOrRenameEntry): T[] | undefined { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. @@ -1559,7 +1565,7 @@ namespace ts { ? program.getSourceFiles().filter(sourceFile => !program.isSourceFileDefaultLibrary(sourceFile)) : program.getSourceFiles(); - return FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined { @@ -1803,25 +1809,36 @@ namespace ts { return ts.getEditsForFileRename(getProgram()!, oldFilePath, newFilePath, host, formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(action: CodeActionCommand): Promise; - function applyCodeActionCommand(action: CodeActionCommand[]): Promise; - function applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + function applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + function applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + function applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; function applyCodeActionCommand(fileName: Path, action: CodeActionCommand): Promise; function applyCodeActionCommand(fileName: Path, action: CodeActionCommand[]): Promise; - function applyCodeActionCommand(fileName: Path | CodeActionCommand | CodeActionCommand[], actionOrUndefined?: CodeActionCommand | CodeActionCommand[]): Promise { - const action = typeof fileName === "string" ? actionOrUndefined! : fileName as CodeActionCommand[]; - return isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName: Path | CodeActionCommand | CodeActionCommand[], actionOrFormatSettingsOrUndefined?: CodeActionCommand | CodeActionCommand[] | FormatCodeSettings): Promise { + const action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined as CodeActionCommand | CodeActionCommand[] : fileName as CodeActionCommand[]; + const formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined as FormatCodeSettings : undefined; + return isArray(action) ? Promise.all(action.map(a => applySingleCodeActionCommand(a, formatSettings))) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action: CodeActionCommand): Promise { + function applySingleCodeActionCommand(action: CodeActionCommand, formatSettings: FormatCodeSettings | undefined): Promise { + const getPath = (path: string): Path => toPath(path, currentDirectory, getCanonicalFileName); switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + const { fileToGenerateTypesFor, outputFileName } = action; + if (!host.inspectValue) return Promise.reject("Host does not implement `installPackage`"); + const valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(valueInfo => { + const fullOut = getPath(outputFileName); + host.writeFile!(fullOut, valueInfoToDeclarationFileText(valueInfo, formatSettings || testFormatSettings)); // TODO: GH#18217 + return { successMessage: `Wrote types to '${fullOut}'` }; + }); + } default: - return Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return Debug.assertNever(action); } } diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index b6174be75e0..d63e16ce801 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -38,7 +38,8 @@ namespace ts.SignatureHelp { return undefined; } - const argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + const isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + const argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); @@ -50,7 +51,7 @@ namespace ts.SignatureHelp { if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } return typeChecker.runWithCancellationToken(cancellationToken, typeChecker => @@ -115,7 +116,7 @@ namespace ts.SignatureHelp { } } - function createJavaScriptSignatureHelpItems(argumentInfo: ArgumentListInfo, program: Program, cancellationToken: CancellationToken): SignatureHelpItems | undefined { + function createJSSignatureHelpItems(argumentInfo: ArgumentListInfo, program: Program, cancellationToken: CancellationToken): SignatureHelpItems | undefined { if (argumentInfo.invocation.kind === InvocationKind.Contextual) return undefined; // See if we can find some symbol with the call expression name that has call signatures. const expression = getExpressionFromInvocation(argumentInfo.invocation); @@ -450,8 +451,8 @@ namespace ts.SignatureHelp { return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node: Node, position: number, sourceFile: SourceFile, checker: TypeChecker): ArgumentListInfo | undefined { - for (let n = node; !isBlock(n) && !isSourceFile(n); n = n.parent) { + function getContainingArgumentInfo(node: Node, position: number, sourceFile: SourceFile, checker: TypeChecker, isManuallyInvoked: boolean): ArgumentListInfo | undefined { + for (let n = node; isManuallyInvoked || (!isBlock(n) && !isSourceFile(n)); n = n.parent) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. Debug.assert(rangeContainsRange(n.parent, n), "Not a subspan", () => `Child: ${Debug.showSyntaxKind(n)}, parent: ${Debug.showSyntaxKind(n.parent)}`); diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index 167bcb6bbac..fcbb02d4023 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -11,7 +11,7 @@ namespace ts { diags.push(createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - const isJsFile = isSourceFileJavaScript(sourceFile); + const isJsFile = isSourceFileJS(sourceFile); check(sourceFile); @@ -36,7 +36,7 @@ namespace ts { if (isJsFile) { switch (node.kind) { case SyntaxKind.FunctionExpression: - const decl = getDeclarationOfJSInitializer(node); + const decl = getDeclarationOfExpando(node); if (decl) { const symbol = decl.symbol; if (symbol && (symbol.exports && symbol.exports.size || symbol.members && symbol.members.size)) { @@ -82,12 +82,12 @@ namespace ts { switch (statement.kind) { case SyntaxKind.VariableStatement: return (statement as VariableStatement).declarationList.declarations.some(decl => - isRequireCall(propertyAccessLeftHandSide(decl.initializer!), /*checkArgumentIsStringLiteralLike*/ true)); // TODO: GH#18217 + !!decl.initializer && isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true)); case SyntaxKind.ExpressionStatement: { const { expression } = statement as ExpressionStatement; if (!isBinaryExpression(expression)) return isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - const kind = getSpecialPropertyAssignmentKind(expression); - return kind === SpecialPropertyAssignmentKind.ExportsProperty || kind === SpecialPropertyAssignmentKind.ModuleExports; + const kind = getAssignmentDeclarationKind(expression); + return kind === AssignmentDeclarationKind.ExportsProperty || kind === AssignmentDeclarationKind.ModuleExports; } default: return false; @@ -132,7 +132,7 @@ namespace ts { // check that a property access expression exists in there and that it is a handler const returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(createDiagnosticForNode(isVariableDeclaration(node.parent) ? node.parent.name : node, Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(createDiagnosticForNode(!node.name && isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) ? node.parent.name : node, Diagnostics.This_may_be_converted_to_an_async_function)); } } @@ -141,8 +141,8 @@ namespace ts { } /** @internal */ - export function getReturnStatementsWithPromiseHandlers(node: Node): Node[] { - const returnStatements: Node[] = []; + export function getReturnStatementsWithPromiseHandlers(node: Node): ReturnStatement[] { + const returnStatements: ReturnStatement[] = []; if (isFunctionLike(node)) { forEachChild(node, visit); } @@ -155,14 +155,8 @@ namespace ts { return; } - if (isReturnStatement(child)) { - forEachChild(child, addHandlers); - } - - function addHandlers(returnChild: Node) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child as ReturnStatement); - } + if (isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } forEachChild(child, visit); @@ -170,8 +164,39 @@ namespace ts { return returnStatements; } - function isPromiseHandler(node: Node): boolean { - return (isCallExpression(node) && isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node: Node): boolean { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + + // ensure all chained calls are valid + let currentNode = node.expression; + while (isPromiseHandler(currentNode) || isPropertyAccessExpression(currentNode)) { + if (isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + + function isPromiseHandler(node: Node): node is CallExpression { + return isCallExpression(node) && (hasPropertyAccessExpressionWithName(node, "then") || hasPropertyAccessExpressionWithName(node, "catch")); + } + + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg: Expression): boolean { + switch (arg.kind) { + case SyntaxKind.NullKeyword: + case SyntaxKind.Identifier: // identifier includes undefined + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + return true; + default: + return false; + } } } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index cc59aa3c0ce..e0728f98a29 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -534,7 +534,7 @@ namespace ts.SymbolDisplay { tags = tagsFromAlias; } - return { displayParts, documentation, symbolKind, tags: tags! }; + return { displayParts, documentation, symbolKind, tags: tags!.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 32d6360e90c..0d45039f5b1 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -209,10 +209,16 @@ namespace ts.textChanges { export type TypeAnnotatable = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertyDeclaration | PropertySignature; + interface JSDocParameter { + declaration: ParameterDeclaration; + typeNode: TypeNode; + isOptional?: boolean; + } + export class ChangeTracker { private readonly changes: Change[] = []; - private readonly newFiles: { readonly oldFile: SourceFile, readonly fileName: string, readonly statements: ReadonlyArray }[] = []; - private readonly classesWithNodesInsertedAtStart = createMap(); // Set implemented as Map + private readonly newFiles: { readonly oldFile: SourceFile | undefined, readonly fileName: string, readonly statements: ReadonlyArray }[] = []; + private readonly classesWithNodesInsertedAtStart = createMap<{ readonly node: ClassDeclaration | InterfaceDeclaration | ObjectLiteralExpression, readonly sourceFile: SourceFile }>(); // Set implemented as Map private readonly deletedNodes: { readonly sourceFile: SourceFile, readonly node: Node | NodeArray }[] = []; public static fromContext(context: TextChangesContext): ChangeTracker { @@ -295,7 +301,7 @@ namespace ts.textChanges { } private insertNodesAt(sourceFile: SourceFile, pos: number, newNodes: ReadonlyArray, options: ReplaceWithMultipleNodesOptions = {}): void { - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile, options, nodes: newNodes, range: { pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, createRange(pos), newNodes, options); } public insertNodeAtTopOfFile(sourceFile: SourceFile, newNode: Statement, blankLineBetween: boolean): void { @@ -312,7 +318,17 @@ namespace ts.textChanges { public insertModifierBefore(sourceFile: SourceFile, modifier: SyntaxKind, before: Node): void { const pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos, end: pos }, createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, createToken(modifier), { suffix: " " }); + } + + public insertLastModifierBefore(sourceFile: SourceFile, modifier: SyntaxKind, before: Node): void { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + + const pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, createToken(modifier), { prefix: " " }); } public insertCommentBeforeLine(sourceFile: SourceFile, lineNumber: number, position: number, commentText: string): void { @@ -329,6 +345,12 @@ namespace ts.textChanges { this.insertText(sourceFile, token.getStart(sourceFile), text); } + public insertCommentThenNewline(sourceFile: SourceFile, character: number, position: number, commentText: string): void { + const token = getTouchingToken(sourceFile, position); + const text = "/**" + commentText + "*/" + this.newLineCharacter + repeatString(" ", character); + this.insertText(sourceFile, token.getStart(sourceFile), text); + } + public replaceRangeWithText(sourceFile: SourceFile, range: TextRange, text: string) { this.changes.push({ kind: ChangeKind.Text, sourceFile, range, text }); } @@ -337,6 +359,23 @@ namespace ts.textChanges { this.replaceRangeWithText(sourceFile, createRange(pos), text); } + public tryInsertJSDocParameters(sourceFile: SourceFile, parameters: JSDocParameter[]) { + if (parameters.length === 0) { + return; + } + const parent = parameters[0].declaration.parent; + const indent = getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; + let commentText = "\n"; + for (const { declaration, typeNode, isOptional } of parameters) { + if (isIdentifier(declaration.name)) { + const printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; + commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); + } + } + commentText += repeatString(" ", indent + 1); + this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); + } + /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ public tryInsertTypeAnnotation(sourceFile: SourceFile, node: TypeAnnotatable, type: TypeNode): void { let endNode: Node | undefined; @@ -355,6 +394,27 @@ namespace ts.textChanges { this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); } + public tryInsertJSDocType(sourceFile: SourceFile, node: Node, type: TypeNode): void { + const printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; + let commentText; + if (isGetAccessorDeclaration(node)) { + commentText = ` @return {${printed}} `; + } + else { + commentText = ` @type {${printed}} `; + node = node.parent; + } + this.insertCommentThenNewline(sourceFile, getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); + } + + private printJSDocParameter(indent: number, printed: string, name: Identifier, isOptionalParameter: boolean | undefined) { + let printName = unescapeLeadingUnderscores(name.escapedText); + if (isOptionalParameter) { + printName = `[${printName}]`; + } + return repeatString(" ", indent) + ` * @param {${printed}} ${printName}\n`; + } + public insertTypeParameters(sourceFile: SourceFile, node: SignatureDeclaration, typeParameters: ReadonlyArray): void { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter const start = (findChildOfKind(node, SyntaxKind.OpenParenToken, sourceFile) || first(node.parameters)).getStart(sourceFile); @@ -403,32 +463,40 @@ namespace ts.textChanges { public insertNodeAtEndOfScope(sourceFile: SourceFile, scope: Node, newNode: Node): void { const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken()!, {}, Position.Start); - this.replaceRange(sourceFile, { pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken()!.pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); } public insertNodeAtClassStart(sourceFile: SourceFile, cls: ClassLikeDeclaration | InterfaceDeclaration, newElement: ClassElement): void { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + } + public insertNodeAtObjectStart(sourceFile: SourceFile, obj: ObjectLiteralExpression, newElement: ObjectLiteralElementLike): void { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + } + + private insertNodeAtStartWorker(sourceFile: SourceFile, cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression, newElement: ClassElement | ObjectLiteralElementLike): void { const clsStart = cls.getStart(sourceFile); const indentation = formatting.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize!; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation, ...this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls) }); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, { indentation, ...this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls) }); } - private getInsertNodeAtClassStartPrefixSuffix(sourceFile: SourceFile, cls: ClassLikeDeclaration | InterfaceDeclaration): { prefix: string, suffix: string } { - if (cls.members.length === 0) { - if (addToSeen(this.classesWithNodesInsertedAtStart, getNodeId(cls), cls)) { + private getInsertNodeAtStartPrefixSuffix(sourceFile: SourceFile, cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression): { prefix: string, suffix: string } { + const comma = isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (addToSeen(this.classesWithNodesInsertedAtStart, getNodeId(cls), { node: cls, sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - const shouldSuffix = (positionsAreOnSameLine as any)(...getClassBraceEnds(cls, sourceFile), sourceFile); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + const shouldSuffix = (positionsAreOnSameLine as any)(...getClassOrObjectBraceEnds(cls, sourceFile), sourceFile); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } } @@ -647,9 +715,8 @@ namespace ts.textChanges { } private finishClassesWithNodesInsertedAtStart(): void { - this.classesWithNodesInsertedAtStart.forEach(cls => { - const sourceFile = cls.getSourceFile(); - const [openBraceEnd, closeBraceEnd] = getClassBraceEnds(cls, sourceFile); + this.classesWithNodesInsertedAtStart.forEach(({ node, sourceFile }) => { + const [openBraceEnd, closeBraceEnd] = getClassOrObjectBraceEnds(node, sourceFile); // For `class C { }` remove the whitespace inside the braces. if (positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { this.deleteRange(sourceFile, createRange(openBraceEnd, closeBraceEnd - 1)); @@ -698,7 +765,7 @@ namespace ts.textChanges { return changes; } - public createNewFile(oldFile: SourceFile, fileName: string, statements: ReadonlyArray) { + public createNewFile(oldFile: SourceFile | undefined, fileName: string, statements: ReadonlyArray) { this.newFiles.push({ oldFile, fileName, statements }); } } @@ -708,12 +775,19 @@ namespace ts.textChanges { return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls: ClassLikeDeclaration | InterfaceDeclaration, sourceFile: SourceFile): [number, number] { + function getClassOrObjectBraceEnds(cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression, sourceFile: SourceFile): [number, number] { return [findChildOfKind(cls, SyntaxKind.OpenBraceToken, sourceFile)!.end, findChildOfKind(cls, SyntaxKind.CloseBraceToken, sourceFile)!.end]; } + function getMembersOrProperties(cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression): NodeArray { + return isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } export type ValidateNonFormattedText = (node: Node, text: string) => void; + export function getNewFileText(statements: ReadonlyArray, scriptKind: ScriptKind, newLineCharacter: string, formatContext: formatting.FormatContext): string { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + namespace changesToText { export function getTextChangesFromChanges(changes: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText | undefined): FileTextChanges[] { return group(changes, c => c.sourceFile.path).map(changesInFile => { @@ -732,13 +806,17 @@ namespace ts.textChanges { }); } - export function newFileChanges(oldFile: SourceFile, fileName: string, statements: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext): FileTextChanges { + export function newFileChanges(oldFile: SourceFile | undefined, fileName: string, statements: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext): FileTextChanges { + const text = newFileChangesWorker(oldFile, getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true }; + } + + export function newFileChangesWorker(oldFile: SourceFile | undefined, scriptKind: ScriptKind, statements: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext): string { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this const nonFormattedText = statements.map(s => getNonformattedText(s, oldFile, newLineCharacter).text).join(newLineCharacter); - const sourceFile = createSourceFile(fileName, nonFormattedText, ScriptTarget.ESNext, /*setParentNodes*/ true); + const sourceFile = createSourceFile("any file name", nonFormattedText, ScriptTarget.ESNext, /*setParentNodes*/ true, scriptKind); const changes = formatting.formatDocument(sourceFile, formatContext); - const text = applyChanges(nonFormattedText, changes); - return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true }; + return applyChanges(nonFormattedText, changes); } function computeNewText(change: Change, sourceFile: SourceFile, newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText | undefined): string { @@ -778,10 +856,10 @@ namespace ts.textChanges { } /** Note: output node may be mutated input node. */ - function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLineCharacter: string): { text: string, node: Node } { + export function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLineCharacter: string): { text: string, node: Node } { const writer = new Writer(newLineCharacter); const newLine = newLineCharacter === "\n" ? NewLineKind.LineFeed : NewLineKind.CarriageReturnLineFeed; - createPrinter({ newLine }, writer).writeNode(EmitHint.Unspecified, node, sourceFile, writer); + createPrinter({ newLine, neverAsciiEscape: true }, writer).writeNode(EmitHint.Unspecified, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } } diff --git a/src/services/transpile.ts b/src/services/transpile.ts index 70ca5b64314..030d2273b62 100644 --- a/src/services/transpile.ts +++ b/src/services/transpile.ts @@ -48,6 +48,7 @@ namespace ts { options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index fee6da0f8a3..6f718b43730 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -69,6 +69,7 @@ "codefixes/inferFromUsage.ts", "codefixes/fixInvalidImportSyntax.ts", "codefixes/fixStrictClassInitialization.ts", + "codefixes/generateTypes.ts", "codefixes/requireInTs.ts", "codefixes/useDefaultImport.ts", "codefixes/fixAddModuleReferTypeMissingTypeof.ts", @@ -82,6 +83,6 @@ "services.ts", "breakpoints.ts", "transform.ts", - "shims.ts" + "shims.ts", ] } diff --git a/src/services/types.ts b/src/services/types.ts index 9bf0edf3150..011c98f9da6 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -231,6 +231,8 @@ namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; + /* @internal */ inspectValue?(options: InspectValueOptions): Promise; + writeFile?(fileName: string, content: string): void; } /* @internal */ @@ -331,9 +333,9 @@ namespace ts { getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -526,12 +528,22 @@ namespace ts { // Publicly, this type is just `{}`. Internally it is a union of all the actions we use. // See `commands?: {}[]` in protocol.ts - export type CodeActionCommand = InstallPackageAction; + export type CodeActionCommand = InstallPackageAction | GenerateTypesAction; export interface InstallPackageAction { - /* @internal */ file: string; - /* @internal */ type: "install package"; - /* @internal */ packageName: string; + /* @internal */ readonly type: "install package"; + /* @internal */ readonly file: string; + /* @internal */ readonly packageName: string; + } + + export interface GenerateTypesAction extends GenerateTypesOptions { + /* @internal */ readonly type: "generate types"; + } + + export interface GenerateTypesOptions { + readonly file: string; // File that was importing fileToGenerateTypesFor; used for formatting options. + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; } /** @@ -607,6 +619,8 @@ namespace ts { } export interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } export interface ReferenceEntry extends DocumentSpan { @@ -717,6 +731,31 @@ namespace ts { indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } + /* @internal */ + export const testFormatSettings: FormatCodeSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; + export interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; @@ -782,15 +821,24 @@ namespace ts { tags?: JSDocTagInfo[]; } - export interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + export type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + export interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + export interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } export interface SignatureHelpParameter { name: string; diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 1c10bc983fd..427c31e5384 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -23,8 +23,10 @@ namespace ts { export function getMeaningFromDeclaration(node: Node): SemanticMeaning { switch (node.kind) { - case SyntaxKind.Parameter: case SyntaxKind.VariableDeclaration: + return isInJSFile(node) && getJSDocEnumTag(node) ? SemanticMeaning.All : SemanticMeaning.Value; + + case SyntaxKind.Parameter: case SyntaxKind.BindingElement: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: @@ -224,6 +226,14 @@ namespace ts { return undefined; } + export function hasPropertyAccessExpressionWithName(node: CallExpression, funcName: string): boolean { + if (!isPropertyAccessExpression(node.expression)) { + return false; + } + + return node.expression.name.text === funcName; + } + export function isJumpStatementTarget(node: Node): node is Identifier & { parent: BreakOrContinueStatement } { return node.kind === SyntaxKind.Identifier && isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -355,23 +365,23 @@ namespace ts { case SyntaxKind.NamespaceImport: return ScriptElementKind.alias; case SyntaxKind.BinaryExpression: - const kind = getSpecialPropertyAssignmentKind(node as BinaryExpression); + const kind = getAssignmentDeclarationKind(node as BinaryExpression); const { right } = node as BinaryExpression; switch (kind) { - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.None: return ScriptElementKind.unknown; - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ModuleExports: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.ModuleExports: const rightKind = getNodeKind(right); return rightKind === ScriptElementKind.unknown ? ScriptElementKind.constElement : rightKind; - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.PrototypeProperty: return isFunctionExpression(right) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement; - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ThisProperty: return ScriptElementKind.memberVariableElement; // property - case SpecialPropertyAssignmentKind.Property: + case AssignmentDeclarationKind.Property: // static method / property return isFunctionExpression(right) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement; - case SpecialPropertyAssignmentKind.Prototype: + case AssignmentDeclarationKind.Prototype: return ScriptElementKind.localClassElement; default: { assertType(kind); @@ -1315,7 +1325,16 @@ namespace ts { }); } - export function getPropertySymbolFromBindingElement(checker: TypeChecker, bindingElement: BindingElement & { name: Identifier }) { + export type ObjectBindingElementWithoutPropertyName = BindingElement & { name: Identifier }; + + export function isObjectBindingElementWithoutPropertyName(bindingElement: Node): bindingElement is ObjectBindingElementWithoutPropertyName { + return isBindingElement(bindingElement) && + isObjectBindingPattern(bindingElement.parent) && + isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + + export function getPropertySymbolFromBindingElement(checker: TypeChecker, bindingElement: ObjectBindingElementWithoutPropertyName) { const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); const propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); if (propSymbol && propSymbol.flags & SymbolFlags.Accessor) { @@ -1654,11 +1673,10 @@ namespace ts { return clone; } - export function getSynthesizedDeepCloneWithRenames(node: T, includeTrivia = true, renameMap?: Map, checker?: TypeChecker, callback?: (originalNode: Node, clone: Node) => any): T { - + export function getSynthesizedDeepCloneWithRenames(node: T, includeTrivia = true, renameMap?: Map, checker?: TypeChecker, callback?: (originalNode: Node, clone: Node) => any): T { let clone; - if (node && isIdentifier(node!) && renameMap && checker) { - const symbol = checker.getSymbolAtLocation(node!); + if (isIdentifier(node) && renameMap && checker) { + const symbol = checker.getSymbolAtLocation(node); const renameInfo = symbol && renameMap.get(String(getSymbolId(symbol))); if (renameInfo) { @@ -1667,11 +1685,11 @@ namespace ts { } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node as NonNullable, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node as NonNullable, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) callback(node!, clone); + if (callback && clone) callback(node, clone); return clone as T; } diff --git a/src/testRunner/compilerRunner.ts b/src/testRunner/compilerRunner.ts index a0af5d88f3b..bb481eca03e 100644 --- a/src/testRunner/compilerRunner.ts +++ b/src/testRunner/compilerRunner.ts @@ -208,7 +208,7 @@ class CompilerTest { public verifyModuleResolution() { if (this.options.traceResolution) { Harness.Baseline.runBaseline(this.justName.replace(/\.tsx?$/, ".trace.json"), - utils.removeTestPathPrefixes(JSON.stringify(this.result.traces, undefined, 4))); + JSON.stringify(this.result.traces.map(utils.sanitizeTraceResolutionLogEntry), undefined, 4)); } } diff --git a/src/testRunner/externalCompileRunner.ts b/src/testRunner/externalCompileRunner.ts index 33d8c15a31f..a8a240a5161 100644 --- a/src/testRunner/externalCompileRunner.ts +++ b/src/testRunner/externalCompileRunner.ts @@ -1,6 +1,6 @@ -const fs = require("fs"); -const path = require("path"); -const del = require("del"); +const fs: typeof import("fs") = require("fs"); +const path: typeof import("path") = require("path"); +const del: typeof import("del") = require("del"); interface ExecResult { stdout: Buffer; @@ -40,7 +40,7 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { const timeout = 600_000; // 10 minutes describe(directoryName, function(this: Mocha.ISuiteCallbackContext) { this.timeout(timeout); - const cp = require("child_process"); + const cp: typeof import("child_process") = require("child_process"); it("should build successfully", () => { let cwd = path.join(Harness.IO.getWorkspaceRoot(), cls.testDir, directoryName); @@ -49,12 +49,9 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { let types: string[] | undefined; if (fs.existsSync(path.join(cwd, "test.json"))) { const submoduleDir = path.join(cwd, directoryName); - const reset = cp.spawnSync("git", ["reset", "HEAD", "--hard"], { cwd: submoduleDir, timeout, shell: true, stdio }); - if (reset.status !== 0) throw new Error(`git reset for ${directoryName} failed: ${reset.stderr.toString()}`); - const clean = cp.spawnSync("git", ["clean", "-f"], { cwd: submoduleDir, timeout, shell: true, stdio }); - if (clean.status !== 0) throw new Error(`git clean for ${directoryName} failed: ${clean.stderr.toString()}`); - const update = cp.spawnSync("git", ["submodule", "update", "--remote", "."], { cwd: submoduleDir, timeout, shell: true, stdio }); - if (update.status !== 0) throw new Error(`git submodule update for ${directoryName} failed: ${update.stderr.toString()}`); + exec("git", ["reset", "HEAD", "--hard"], { cwd: submoduleDir }); + exec("git", ["clean", "-f"], { cwd: submoduleDir }); + exec("git", ["submodule", "update", "--init", "--remote", "."], { cwd: submoduleDir }); const config = JSON.parse(fs.readFileSync(path.join(cwd, "test.json"), { encoding: "utf8" })) as UserConfig; ts.Debug.assert(!!config.types, "Bad format from test.json: Types field must be present."); @@ -69,18 +66,23 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { if (fs.existsSync(path.join(cwd, "node_modules"))) { del.sync(path.join(cwd, "node_modules"), { force: true }); } - const install = cp.spawnSync(`npm`, ["i", "--ignore-scripts"], { cwd, timeout: timeout / 2, shell: true, stdio }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure - if (install.status !== 0) throw new Error(`NPM Install for ${directoryName} failed: ${install.stderr.toString()}`); + exec("npm", ["i", "--ignore-scripts"], { cwd, timeout: timeout / 2 }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure } const args = [path.join(Harness.IO.getWorkspaceRoot(), "built/local/tsc.js")]; if (types) { args.push("--types", types.join(",")); // Also actually install those types (for, eg, the js projects which need node) - const install = cp.spawnSync(`npm`, ["i", ...types.map(t => `@types/${t}`), "--no-save", "--ignore-scripts"], { cwd: originalCwd, timeout: timeout / 2, shell: true, stdio }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure - if (install.status !== 0) throw new Error(`NPM Install types for ${directoryName} failed: ${install.stderr.toString()}`); + exec("npm", ["i", ...types.map(t => `@types/${t}`), "--no-save", "--ignore-scripts"], { cwd: originalCwd, timeout: timeout / 2 }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure } args.push("--noEmit"); Harness.Baseline.runBaseline(`${cls.kind()}/${directoryName}.log`, cls.report(cp.spawnSync(`node`, args, { cwd, timeout, shell: true }), cwd)); + + function exec(command: string, args: string[], options: { cwd: string, timeout?: number }): void { + const res = cp.spawnSync(command, args, { timeout, shell: true, stdio, ...options }); + if (res.status !== 0) { + throw new Error(`${command} ${args.join(" ")} for ${directoryName} failed: ${res.stderr && res.stderr.toString()}`); + } + } }); }); } diff --git a/src/testRunner/runner.ts b/src/testRunner/runner.ts index 6e430b08734..e528678ab83 100644 --- a/src/testRunner/runner.ts +++ b/src/testRunner/runner.ts @@ -138,7 +138,6 @@ function handleTestConfig() { case "compiler": runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance)); runners.push(new CompilerBaselineRunner(CompilerTestType.Regressions)); - runners.push(new project.ProjectRunner()); break; case "conformance": runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance)); diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 27dca8296ed..42edf839964 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -74,6 +74,7 @@ "unittests/publicApi.ts", "unittests/reuseProgramStructure.ts", "unittests/session.ts", + "unittests/semver.ts", "unittests/symbolWalker.ts", "unittests/telemetry.ts", "unittests/textChanges.ts", diff --git a/src/testRunner/unittests/compileOnSave.ts b/src/testRunner/unittests/compileOnSave.ts index 49d1659deec..4b98d71ef0a 100644 --- a/src/testRunner/unittests/compileOnSave.ts +++ b/src/testRunner/unittests/compileOnSave.ts @@ -36,7 +36,7 @@ namespace ts.projectSystem { typingsInstaller: typingsInstaller || server.nullTypingsInstaller, byteLength: Utils.byteLength, hrtime: process.hrtime, - logger: nullLogger, + logger: createHasErrorMessageLogger().logger, canUseEvents: false }; return new server.Session(opts); diff --git a/src/testRunner/unittests/configurationExtension.ts b/src/testRunner/unittests/configurationExtension.ts index 012b8e0d2fa..fbb4950b9a5 100644 --- a/src/testRunner/unittests/configurationExtension.ts +++ b/src/testRunner/unittests/configurationExtension.ts @@ -96,6 +96,11 @@ namespace ts { include: null, files: ["../main.ts"] }), + "dev/configs/fifth.json": JSON.stringify({ + extends: "./fourth", + include: ["../tests/utils.ts"], + files: [] + }), "dev/extends.json": JSON.stringify({ extends: 42 }), "dev/extends2.json": JSON.stringify({ extends: "configs/base" }), "dev/main.ts": "", @@ -244,6 +249,29 @@ namespace ts { }, [ combinePaths(basePath, "main.ts") ]); + + testSuccess("can overwrite top-level files using extended []", "configs/fifth.json", { + allowJs: true, + noImplicitAny: true, + strictNullChecks: true, + module: ModuleKind.System + }, [ + combinePaths(basePath, "tests/utils.ts") + ]); + + it("adds extendedSourceFiles only once", () => { + const sourceFile = readJsonConfigFile("configs/fourth.json", (path) => host.readFile(path)); + const dir = combinePaths(basePath, "configs"); + const expected = [ + combinePaths(dir, "third.json"), + combinePaths(dir, "second.json"), + combinePaths(dir, "base.json"), + ]; + parseJsonSourceFileConfigFileContent(sourceFile, host, dir, {}, "fourth.json"); + assert.deepEqual(sourceFile.extendedSourceFiles, expected); + parseJsonSourceFileConfigFileContent(sourceFile, host, dir, {}, "fourth.json"); + assert.deepEqual(sourceFile.extendedSourceFiles, expected); + }); }); }); }); diff --git a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/convertCompilerOptionsFromJson.ts index 3b422e9a645..327bf523160 100644 --- a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/convertCompilerOptionsFromJson.ts @@ -1,33 +1,50 @@ namespace ts { describe("convertCompilerOptionsFromJson", () => { - function assertCompilerOptions(json: any, configFileName: string, expectedResult: { compilerOptions: CompilerOptions, errors: Diagnostic[] }) { + const formatDiagnosticHost: FormatDiagnosticsHost = { + getCurrentDirectory: () => "/apath/", + getCanonicalFileName: createGetCanonicalFileName(/*useCaseSensitiveFileNames*/ true), + getNewLine: () => "\n" + }; + + interface ExpectedResultWithParsingSuccess { + compilerOptions: CompilerOptions; + errors: ReadonlyArray; + } + + interface ExpectedResultWithParsingFailure { + compilerOptions: CompilerOptions; + hasParseErrors: true; + } + + type ExpectedResult = ExpectedResultWithParsingSuccess | ExpectedResultWithParsingFailure; + + function isExpectedResultWithParsingFailure(expectedResult: ExpectedResult): expectedResult is ExpectedResultWithParsingFailure { + return !!(expectedResult as ExpectedResultWithParsingFailure).hasParseErrors; + } + + function assertCompilerOptions(json: any, configFileName: string, expectedResult: ExpectedResultWithParsingSuccess) { assertCompilerOptionsWithJson(json, configFileName, expectedResult); assertCompilerOptionsWithJsonNode(json, configFileName, expectedResult); } - function assertCompilerOptionsWithJson(json: any, configFileName: string, expectedResult: { compilerOptions: CompilerOptions, errors: Diagnostic[] }) { - const { options: actualCompilerOptions, errors: actualErrors} = convertCompilerOptionsFromJson(json.compilerOptions, "/apath/", configFileName); + function assertCompilerOptionsWithJson(json: any, configFileName: string, expectedResult: ExpectedResultWithParsingSuccess) { + const { options: actualCompilerOptions, errors: actualErrors } = convertCompilerOptionsFromJson(json.compilerOptions, "/apath/", configFileName); const parsedCompilerOptions = JSON.stringify(actualCompilerOptions); const expectedCompilerOptions = JSON.stringify({ ...expectedResult.compilerOptions, configFilePath: configFileName }); assert.equal(parsedCompilerOptions, expectedCompilerOptions); - const expectedErrors = expectedResult.errors; - assert.isTrue(expectedResult.errors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedResult.errors)}. Actual error: ${JSON.stringify(actualErrors)}.`); - for (let i = 0; i < actualErrors.length; i++) { - const actualError = actualErrors[i]; - const expectedError = expectedErrors[i]; - assert.equal(actualError.code, expectedError.code); - assert.equal(actualError.category, expectedError.category); - assert.equal(actualError.messageText, expectedError.messageText); - } + verifyErrors(actualErrors, expectedResult.errors, /*ignoreLocation*/ true); } - function assertCompilerOptionsWithJsonNode(json: any, configFileName: string, expectedResult: { compilerOptions: CompilerOptions, errors: Diagnostic[] }) { - const fileText = JSON.stringify(json); + function assertCompilerOptionsWithJsonNode(json: any, configFileName: string, expectedResult: ExpectedResultWithParsingSuccess) { + assertCompilerOptionsWithJsonText(JSON.stringify(json), configFileName, expectedResult); + } + + function assertCompilerOptionsWithJsonText(fileText: string, configFileName: string, expectedResult: ExpectedResult) { const result = parseJsonText(configFileName, fileText); - assert(!result.parseDiagnostics.length); assert(!!result.endOfFileToken); + assert.equal(!!result.parseDiagnostics.length, isExpectedResultWithParsingFailure(expectedResult)); const host: ParseConfigHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ false, { cwd: "/apath/" })); const { options: actualCompilerOptions, errors: actualParseErrors } = parseJsonSourceFileConfigFileContent(result, host, "/apath/", /*existingOptions*/ undefined, configFileName); expectedResult.compilerOptions.configFilePath = configFileName; @@ -37,17 +54,32 @@ namespace ts { assert.equal(parsedCompilerOptions, expectedCompilerOptions); assert.equal(actualCompilerOptions.configFile, result); - const actualErrors = filter(actualParseErrors, error => error.code !== Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code); - const expectedErrors = expectedResult.errors; - assert.isTrue(expectedResult.errors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedResult.errors)}. Actual error: ${JSON.stringify(actualErrors)}.`); + if (!isExpectedResultWithParsingFailure(expectedResult)) { + verifyErrors(actualParseErrors.filter(error => error.code !== Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code), expectedResult.errors); + } + } + + function verifyErrors(actualErrors: Diagnostic[], expectedErrors: ReadonlyArray, ignoreLocation?: boolean) { + assert.isTrue(expectedErrors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedErrors.map(getDiagnosticString), undefined, " ")}. Actual error: ${JSON.stringify(actualErrors.map(getDiagnosticString), undefined, " ")}.`); for (let i = 0; i < actualErrors.length; i++) { const actualError = actualErrors[i]; const expectedError = expectedErrors[i]; + assert.equal(actualError.code, expectedError.code, `Expected error-code: ${JSON.stringify(expectedError.code)}. Actual error-code: ${JSON.stringify(actualError.code)}.`); assert.equal(actualError.category, expectedError.category, `Expected error-category: ${JSON.stringify(expectedError.category)}. Actual error-category: ${JSON.stringify(actualError.category)}.`); - assert(actualError.file); - assert(actualError.start); - assert(actualError.length); + if (!ignoreLocation) { + assert(actualError.file); + assert(actualError.start); + assert(actualError.length); + } + } + + function getDiagnosticString(diagnostic: Diagnostic) { + if (ignoreLocation) { + const { file, ...rest } = diagnostic; + diagnostic = { file: undefined, ...rest }; + } + return formatDiagnostic(diagnostic, formatDiagnosticHost); } } @@ -539,5 +571,36 @@ namespace ts { } ); }); + + it("Convert tsconfig options when there are multiple invalid strings", () => { + assertCompilerOptionsWithJsonText(`{ + "compilerOptions": { + "target": "<%- options.useTsWithBabel ? 'esnext' : 'es5' %>", + "module": "esnext", + <%_ if (options.classComponent) { _%> + "experimentalDecorators": true, + <%_ } _%> + "sourceMap": true, + "types": [ + "webpack-env"<% if (hasMocha || hasJest) { %>,<% } %> + <%_ if (hasMocha) { _%> + "mocha", + "chai" + <%_ } else if (hasJest) { _%> + "jest" + <%_ } _%> + ] + } +} +`, "tsconfig.json", + { + compilerOptions: { + target: undefined, + module: ModuleKind.ESNext + }, + hasParseErrors: true + } + ); + }); }); } diff --git a/src/testRunner/unittests/convertToAsyncFunction.ts b/src/testRunner/unittests/convertToAsyncFunction.ts index 99788e1310e..21c6a29f8e4 100644 --- a/src/testRunner/unittests/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/convertToAsyncFunction.ts @@ -1,68 +1,4 @@ namespace ts { - interface Range { - pos: number; - end: number; - name: string; - } - - interface Test { - source: string; - ranges: Map; - } - - function getTest(source: string): Test { - const activeRanges: Range[] = []; - let text = ""; - let lastPos = 0; - let pos = 0; - const ranges = createMap(); - - while (pos < source.length) { - if (source.charCodeAt(pos) === CharacterCodes.openBracket && - (source.charCodeAt(pos + 1) === CharacterCodes.hash || source.charCodeAt(pos + 1) === CharacterCodes.$)) { - const saved = pos; - pos += 2; - const s = pos; - consumeIdentifier(); - const e = pos; - if (source.charCodeAt(pos) === CharacterCodes.bar) { - pos++; - text += source.substring(lastPos, saved); - const name = s === e - ? source.charCodeAt(saved + 1) === CharacterCodes.hash ? "selection" : "extracted" - : source.substring(s, e); - activeRanges.push({ name, pos: text.length, end: undefined! }); - lastPos = pos; - continue; - } - else { - pos = saved; - } - } - else if (source.charCodeAt(pos) === CharacterCodes.bar && source.charCodeAt(pos + 1) === CharacterCodes.closeBracket) { - text += source.substring(lastPos, pos); - activeRanges[activeRanges.length - 1].end = text.length; - const range = activeRanges.pop()!; - if (range.name in ranges) { - throw new Error(`Duplicate name of range ${range.name}`); - } - ranges.set(range.name, range); - pos += 2; - lastPos = pos; - continue; - } - pos++; - } - text += source.substring(lastPos, pos); - - function consumeIdentifier() { - while (isIdentifierPart(source.charCodeAt(pos), ScriptTarget.Latest)) { - pos++; - } - } - return { source: text, ranges }; - } - const libFile: TestFSWithWatch.File = { path: "/a/lib/lib.d.ts", content: `/// @@ -319,19 +255,22 @@ interface String { charAt: any; } interface Array {}` }; - function testConvertToAsyncFunction(caption: string, text: string, baselineFolder: string, diagnosticDescription: DiagnosticMessage, codeFixDescription: DiagnosticMessage, includeLib?: boolean) { - const t = getTest(text); + function testConvertToAsyncFunction(caption: string, text: string, baselineFolder: string, includeLib?: boolean, expectFailure = false) { + const t = extractTest(text); const selectionRange = t.ranges.get("selection")!; if (!selectionRange) { throw new Error(`Test ${caption} does not specify selection range`); } - [Extension.Ts, Extension.Js].forEach(extension => + const extensions = expectFailure ? [Extension.Ts] : [Extension.Ts, Extension.Js]; + + extensions.forEach(extension => it(`${caption} [${extension}]`, () => runBaseline(extension))); function runBaseline(extension: Extension) { const path = "/a" + extension; - const program = makeProgram({ path, content: t.source }, includeLib)!; + const languageService = makeLanguageService({ path, content: t.source }, includeLib); + const program = languageService.getProgram()!; if (hasSyntacticDiagnostics(program)) { // Don't bother generating JS baselines for inputs that aren't valid JS. @@ -345,10 +284,6 @@ interface Array {}` }; const sourceFile = program.getSourceFile(path)!; - const host = projectSystem.createServerHost([f, libFile]); - const projectService = projectSystem.createProjectService(host); - projectService.openClientFile(f.path); - const languageService = projectService.inferredProjects[0].getLanguageService(); const context: CodeFixContext = { errorCode: 80006, span: { start: selectionRange.pos, length: selectionRange.end - selectionRange.pos }, @@ -357,41 +292,49 @@ interface Array {}` cancellationToken: { throwIfCancellationRequested: noop, isCancellationRequested: returnFalse }, preferences: emptyOptions, host: notImplementedHost, - formatContext: formatting.getFormatContext(testFormatOptions) + formatContext: formatting.getFormatContext(testFormatSettings) }; const diagnostics = languageService.getSuggestionDiagnostics(f.path); - const diagnostic = find(diagnostics, diagnostic => diagnostic.messageText === diagnosticDescription.message); - assert.exists(diagnostic); - assert.equal(diagnostic!.start, context.span.start); - assert.equal(diagnostic!.length, context.span.length); + const diagnostic = find(diagnostics, diagnostic => diagnostic.messageText === Diagnostics.This_may_be_converted_to_an_async_function.message && + diagnostic.start === context.span.start && diagnostic.length === context.span.length); + if (expectFailure) { + assert.isUndefined(diagnostic); + } + else { + assert.exists(diagnostic); + } const actions = codefix.getFixes(context); - const action = find(actions, action => action.description === codeFixDescription.message)!; - assert.exists(action); + const action = find(actions, action => action.description === Diagnostics.Convert_to_async_function.message); + if (expectFailure) { + assert.isNotTrue(action && action.changes.length > 0); + return; + } + + assert.isTrue(action && action.changes.length > 0); const data: string[] = []; data.push(`// ==ORIGINAL==`); data.push(text.replace("[#|", "/*[#|*/").replace("|]", "/*|]*/")); - const changes = action.changes; + const changes = action!.changes; assert.lengthOf(changes, 1); - data.push(`// ==ASYNC FUNCTION::${action.description}==`); + data.push(`// ==ASYNC FUNCTION::${action!.description}==`); const newText = textChanges.applyChanges(sourceFile.text, changes[0].textChanges); data.push(newText); - const diagProgram = makeProgram({ path, content: newText }, includeLib)!; + const diagProgram = makeLanguageService({ path, content: newText }, includeLib).getProgram()!; assert.isFalse(hasSyntacticDiagnostics(diagProgram)); Harness.Baseline.runBaseline(`${baselineFolder}/${caption}${extension}`, data.join(newLineCharacter)); } - function makeProgram(f: { path: string, content: string }, includeLib?: boolean) { + function makeLanguageService(f: { path: string, content: string }, includeLib?: boolean) { const host = projectSystem.createServerHost(includeLib ? [f, libFile] : [f]); // libFile is expensive to parse repeatedly - only test when required const projectService = projectSystem.createProjectService(host); projectService.openClientFile(f.path); - const program = projectService.inferredProjects[0].getLanguageService().getProgram(); - return program; + return projectService.inferredProjects[0].getLanguageService(); } function hasSyntacticDiagnostics(program: Program) { @@ -400,27 +343,6 @@ interface Array {}` } } - function testConvertToAsyncFunctionFailed(caption: string, text: string, description: DiagnosticMessage) { - it(caption, () => { - const t = extractTest(text); - const selectionRange = t.ranges.get("selection"); - if (!selectionRange) { - throw new Error(`Test ${caption} does not specify selection range`); - } - const f = { - path: "/a.ts", - content: t.source - }; - const host = projectSystem.createServerHost([f, libFile]); - const projectService = projectSystem.createProjectService(host); - projectService.openClientFile(f.path); - const languageService = projectService.inferredProjects[0].getLanguageService(); - - const actions = languageService.getSuggestionDiagnostics(f.path); - assert.isUndefined(find(actions, action => action.messageText === description.message)); - }); - } - describe("convertToAsyncFunctions", () => { _testConvertToAsyncFunction("convertToAsyncFunction_basic", ` function [#|f|](): Promise{ @@ -494,6 +416,20 @@ function [#|f|](): Promise { return fetch('https://typescriptlang.org').then( () => console.log("done") ); }` ); + _testConvertToAsyncFunction("convertToAsyncFunction_IgnoreArgs3", ` +function [#|f|](): Promise { + return fetch('https://typescriptlang.org').then( () => console.log("almost done") ).then( () => console.log("done") ); +}` + ); + _testConvertToAsyncFunction("convertToAsyncFunction_IgnoreArgs4", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(res); +} +function res(){ + console.log("done"); +}` + ); + _testConvertToAsyncFunction("convertToAsyncFunction_Method", ` class Parser { [#|f|]():Promise { @@ -545,6 +481,18 @@ function [#|f|]():Promise { function [#|f|]():Promise { return fetch('https://typescriptlang.org').catch(rej => console.log(rej)); } +` + ); + _testConvertToAsyncFunction("convertToAsyncFunction_NoRes4", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(undefined, rejection => console.log("rejected:", rejection)); +} +` + ); + _testConvertToAsyncFunction("convertToAsyncFunction_NoCatchHandler", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(x => x.statusText).catch(undefined); +} ` ); _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestion", ` @@ -823,7 +771,7 @@ function [#|f|](): Promise { } return x.then(resp => { var blob = resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); - return fetch("https://micorosft.com").then(res => console.log("Another one!")); + return fetch("https://microsoft.com").then(res => console.log("Another one!")); }); } ` @@ -889,7 +837,7 @@ function [#|f|]() { ); _testConvertToAsyncFunction("convertToAsyncFunction_Scope1", ` function [#|f|]() { - var var1:Promise, var2; + var var1: Response, var2; return fetch('https://typescriptlang.org').then( _ => Promise.resolve().then( res => { var2 = "test"; @@ -1157,7 +1105,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NestedFunction", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NestedFunctionWrongLocation", ` function [#|f|]() { function fn2(){ function fn3(){ @@ -1167,6 +1115,18 @@ function [#|f|]() { } return fn2(); } +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_NestedFunctionRightLocation", ` +function f() { + function fn2(){ + function [#|fn3|](){ + return fetch("https://typescriptlang.org").then(res => console.log(res)); + } + return fn3(); + } + return fn2(); +} `); _testConvertToAsyncFunction("convertToAsyncFunction_UntypedFunction", ` @@ -1194,14 +1154,126 @@ const [#|foo|] = function () { } `); + _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionWithName", ` +const foo = function [#|f|]() { + return fetch('https://typescriptlang.org').then(result => { console.log(result) }); +} +`); + _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionAssignedToBindingPattern", ` +const { length } = [#|function|] () { + return fetch('https://typescriptlang.org').then(result => { console.log(result) }); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParams", ` +function [#|f|]() { + return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_bindingPattern", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(res); +} +function res({ status, trailer }){ + console.log(status); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_bindingPatternNameCollision", ` +function [#|f|]() { + const result = 'https://typescriptlang.org'; + return fetch(result).then(res); +} +function res({ status, trailer }){ + console.log(status); +} +`); + + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunction", ` +function [#|f|]() { + return Promise.resolve().then(f ? (x => x) : (y => y)); +} +`); + + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunctionNotLastInChain", ` +function [#|f|]() { + return Promise.resolve().then(f ? (x => x) : (y => y)).then(q => q); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_runEffectfulContinuation", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(res).then(_ => console.log("done")); +} +function res(result) { + return Promise.resolve().then(x => console.log(result)); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromise", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText.length)).then(x => console.log(x + 5)); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseInBlock", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(s => { return Promise.resolve(s.statusText.length) }).then(x => x + 5); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsFixablePromise", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText).then(st => st.length)).then(x => console.log(x + 5)); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseLastInChain", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText.length)); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsRejectedPromiseInTryBlock", ` +function [#|f|]() { + return Promise.resolve(1) + .then(x => Promise.reject(x)) + .catch(err => console.log(err)); +} +`); + +_testConvertToAsyncFunction("convertToAsyncFunction_nestedPromises", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(x => Promise.resolve(3).then(y => Promise.resolve(x.statusText.length + y))); +} +`); +_testConvertToAsyncFunction("convertToAsyncFunction_noArgs", ` +function delay(millis: number): Promise { + throw "no" +} + +function [#|main2|]() { + console.log("Please wait. Loading."); + return delay(500) + .then(() => { console.log("."); return delay(500); }) + .then(() => { console.log("."); return delay(500); }) + .then(() => { console.log("."); return delay(500); }) +} +`); +_testConvertToAsyncFunction("convertToAsyncFunction_exportModifier", ` +export function [#|foo|]() { + return fetch('https://typescriptlang.org').then(s => console.log(s)); +} +`); }); function _testConvertToAsyncFunction(caption: string, text: string) { - testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", Diagnostics.This_may_be_converted_to_an_async_function, Diagnostics.Convert_to_async_function, /*includeLib*/ true); + testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true); } function _testConvertToAsyncFunctionFailed(caption: string, text: string) { - testConvertToAsyncFunctionFailed(caption, text, Diagnostics.Convert_to_async_function); + testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true, /*expectFailure*/ true); } -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/extractTestHelpers.ts b/src/testRunner/unittests/extractTestHelpers.ts index 6e46c1304ab..6a74a637e92 100644 --- a/src/testRunner/unittests/extractTestHelpers.ts +++ b/src/testRunner/unittests/extractTestHelpers.ts @@ -64,27 +64,6 @@ namespace ts { } export const newLineCharacter = "\n"; - export const testFormatOptions: FormatCodeSettings = { - indentSize: 4, - tabSize: 4, - newLineCharacter, - convertTabsToSpaces: true, - indentStyle: IndentStyle.Smart, - insertSpaceAfterConstructor: false, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceBeforeFunctionParenthesis: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - }; export const notImplementedHost: LanguageServiceHost = { getCompilationSettings: notImplemented, @@ -123,7 +102,7 @@ namespace ts { startPosition: selectionRange.pos, endPosition: selectionRange.end, host: notImplementedHost, - formatContext: formatting.getFormatContext(testFormatOptions), + formatContext: formatting.getFormatContext(testFormatSettings), preferences: emptyOptions, }; const rangeToExtract = refactor.extractSymbol.getRangeToExtract(sourceFile, createTextSpanFromRange(selectionRange)); @@ -185,7 +164,7 @@ namespace ts { startPosition: selectionRange.pos, endPosition: selectionRange.end, host: notImplementedHost, - formatContext: formatting.getFormatContext(testFormatOptions), + formatContext: formatting.getFormatContext(testFormatSettings), preferences: emptyOptions, }; const rangeToExtract = refactor.extractSymbol.getRangeToExtract(sourceFile, createTextSpanFromRange(selectionRange)); diff --git a/src/testRunner/unittests/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index 7a9e4278c57..27331d6d007 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -83,7 +83,7 @@ namespace ts { describe("Node module resolution - relative paths", () => { function testLoadAsFile(containingFileName: string, moduleFileNameNoExt: string, moduleName: string): void { - for (const ext of supportedTypeScriptExtensions) { + for (const ext of supportedTSExtensions) { test(ext, /*hasDirectoryExists*/ false); test(ext, /*hasDirectoryExists*/ true); } @@ -96,7 +96,7 @@ namespace ts { const failedLookupLocations: string[] = []; const dir = getDirectoryPath(containingFileName); - for (const e of supportedTypeScriptExtensions) { + for (const e of supportedTSExtensions) { if (e === ext) { break; } @@ -137,7 +137,7 @@ namespace ts { const resolution = nodeModuleNameResolver(moduleName, containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, packageJson, moduleFile)); checkResolvedModule(resolution.resolvedModule, createResolvedModule(moduleFile.name)); // expect three failed lookup location - attempt to load module as file with all supported extensions - assert.equal(resolution.failedLookupLocations.length, supportedTypeScriptExtensions.length); + assert.equal(resolution.failedLookupLocations.length, supportedTSExtensions.length); } } @@ -1104,14 +1104,18 @@ import b = require("./moduleB"); }); describe("Type reference directive resolution: ", () => { - function test(typesRoot: string, typeDirective: string, primary: boolean, initialFile: File, targetFile: File, ...otherFiles: File[]) { - const host = createModuleResolutionHost(/*hasDirectoryExists*/ false, ...[initialFile, targetFile].concat(...otherFiles)); - const result = resolveTypeReferenceDirective(typeDirective, initialFile.name, { typeRoots: [typesRoot] }, host); + function testWorker(hasDirectoryExists: boolean, typesRoot: string | undefined, typeDirective: string, primary: boolean, initialFile: File, targetFile: File, ...otherFiles: File[]) { + const host = createModuleResolutionHost(hasDirectoryExists, ...[initialFile, targetFile].concat(...otherFiles)); + const result = resolveTypeReferenceDirective(typeDirective, initialFile.name, typesRoot ? { typeRoots: [typesRoot] } : {}, host); assert(result.resolvedTypeReferenceDirective!.resolvedFileName !== undefined, "expected type directive to be resolved"); assert.equal(result.resolvedTypeReferenceDirective!.resolvedFileName, targetFile.name, "unexpected result of type reference resolution"); assert.equal(result.resolvedTypeReferenceDirective!.primary, primary, "unexpected 'primary' value"); } + function test(typesRoot: string, typeDirective: string, primary: boolean, initialFile: File, targetFile: File, ...otherFiles: File[]) { + testWorker(/*hasDirectoryExists*/ false, typesRoot, typeDirective, primary, initialFile, targetFile, ...otherFiles); + } + it("Can be resolved from primary location", () => { { const f1 = { name: "/root/src/app.ts" }; @@ -1194,7 +1198,7 @@ import b = require("./moduleB"); const names = map(files, f => f.name); const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES2015)), f => f.fileName); const compilerHost: CompilerHost = { - fileExists : fileName => sourceFiles.has(fileName), + fileExists: fileName => sourceFiles.has(fileName), getSourceFile: fileName => sourceFiles.get(fileName), getDefaultLibFileName: () => "lib.d.ts", writeFile: notImplemented, @@ -1219,7 +1223,7 @@ import b = require("./moduleB"); assert.equal(diagnostics1[0].messageText, diagnostics2[0].messageText, "expected one diagnostic"); }); - it ("Modules in the same .d.ts file are preferred to external files", () => { + it("Modules in the same .d.ts file are preferred to external files", () => { const f = { name: "/a/b/c/c/app.d.ts", content: ` @@ -1233,7 +1237,7 @@ import b = require("./moduleB"); }; const file = createSourceFile(f.name, f.content, ScriptTarget.ES2015); const compilerHost: CompilerHost = { - fileExists : fileName => fileName === file.fileName, + fileExists: fileName => fileName === file.fileName, getSourceFile: fileName => fileName === file.fileName ? file : undefined, getDefaultLibFileName: () => "lib.d.ts", writeFile: notImplemented, @@ -1248,7 +1252,7 @@ import b = require("./moduleB"); createProgram([f.name], {}, compilerHost); }); - it ("Modules in .ts file are not checked in the same file", () => { + it("Modules in .ts file are not checked in the same file", () => { const f = { name: "/a/b/c/c/app.ts", content: ` @@ -1262,7 +1266,7 @@ import b = require("./moduleB"); }; const file = createSourceFile(f.name, f.content, ScriptTarget.ES2015); const compilerHost: CompilerHost = { - fileExists : fileName => fileName === file.fileName, + fileExists: fileName => fileName === file.fileName, getSourceFile: fileName => fileName === file.fileName ? file : undefined, getDefaultLibFileName: () => "lib.d.ts", writeFile: notImplemented, @@ -1279,5 +1283,15 @@ import b = require("./moduleB"); }; createProgram([f.name], {}, compilerHost); }); + describe("can be resolved when typeReferenceDirective is relative and in a sibling folder", () => { + const initialFile = { name: "/root/src/background/app.ts" }; + const targetFile = { name: "/root/src/typedefs/filesystem.d.ts" }; + it("when host doesnt have directoryExists", () => { + testWorker(/*hasDirectoryExists*/ false, /*typesRoot*/ undefined, /*typeDirective*/ "../typedefs/filesystem", /*primary*/ false, initialFile, targetFile); + }); + it("when host has directoryExists", () => { + testWorker(/*hasDirectoryExists*/ true, /*typesRoot*/ undefined, /*typeDirective*/ "../typedefs/filesystem", /*primary*/ false, initialFile, targetFile); + }); + }); }); } diff --git a/src/testRunner/unittests/organizeImports.ts b/src/testRunner/unittests/organizeImports.ts index b4f54afa21b..355292c6d89 100644 --- a/src/testRunner/unittests/organizeImports.ts +++ b/src/testRunner/unittests/organizeImports.ts @@ -270,7 +270,7 @@ export const Other = 1; content: "function F() { }", }; const languageService = makeLanguageService(testFile); - const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, testFormatOptions, emptyOptions); + const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, testFormatSettings, emptyOptions); assert.isEmpty(changes); }); @@ -741,7 +741,7 @@ export * from "lib"; function runBaseline(baselinePath: string, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) { const { path: testPath, content: testContent } = testFile; const languageService = makeLanguageService(testFile, ...otherFiles); - const changes = languageService.organizeImports({ type: "file", fileName: testPath }, testFormatOptions, emptyOptions); + const changes = languageService.organizeImports({ type: "file", fileName: testPath }, testFormatSettings, emptyOptions); assert.equal(changes.length, 1); assert.equal(changes[0].fileName, testPath); diff --git a/src/testRunner/unittests/programMissingFiles.ts b/src/testRunner/unittests/programMissingFiles.ts index 37d4c791196..eb68e3bd665 100644 --- a/src/testRunner/unittests/programMissingFiles.ts +++ b/src/testRunner/unittests/programMissingFiles.ts @@ -98,4 +98,27 @@ namespace ts { ]); }); }); + + describe("Program.isSourceFileFromExternalLibrary", () => { + it("works on redirect files", () => { + // In this example '/node_modules/foo/index.d.ts' will redirect to '/node_modules/bar/node_modules/foo/index.d.ts'. + const a = new documents.TextDocument("/a.ts", 'import * as bar from "bar"; import * as foo from "foo";'); + const bar = new documents.TextDocument("/node_modules/bar/index.d.ts", 'import * as foo from "foo";'); + const fooPackageJsonText = '{ "name": "foo", "version": "1.2.3" }'; + const fooIndexText = "export const x: number;"; + const barFooPackage = new documents.TextDocument("/node_modules/bar/node_modules/foo/package.json", fooPackageJsonText); + const barFooIndex = new documents.TextDocument("/node_modules/bar/node_modules/foo/index.d.ts", fooIndexText); + const fooPackage = new documents.TextDocument("/node_modules/foo/package.json", fooPackageJsonText); + const fooIndex = new documents.TextDocument("/node_modules/foo/index.d.ts", fooIndexText); + + const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [a, bar, barFooPackage, barFooIndex, fooPackage, fooIndex], cwd: "/" }); + const program = createProgram(["/a.ts"], emptyOptions, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed })); + + for (const file of [a, bar, barFooIndex, fooIndex]) { + const isExternalExpected = file !== a; + const isExternalActual = program.isSourceFileFromExternalLibrary(program.getSourceFile(file.file)!); + assert.equal(isExternalActual, isExternalExpected, `Expected ${file.file} isSourceFileFromExternalLibrary to be ${isExternalExpected}, got ${isExternalActual}`); + } + }); + }); } diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index f0f9cc6493b..0ab50a65105 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -104,7 +104,7 @@ namespace ts { return file; } - export function createTestCompilerHost(texts: ReadonlyArray, target: ScriptTarget, oldProgram?: ProgramWithSourceTexts): TestCompilerHost { + export function createTestCompilerHost(texts: ReadonlyArray, target: ScriptTarget, oldProgram?: ProgramWithSourceTexts, useGetSourceFileByPath?: boolean) { const files = arrayToMap(texts, t => t.name, t => { if (oldProgram) { let oldFile = oldProgram.getSourceFile(t.name); @@ -117,55 +117,47 @@ namespace ts { } return createSourceFileWithText(t.name, t.text, target); }); + const useCaseSensitiveFileNames = sys && sys.useCaseSensitiveFileNames; + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); const trace: string[] = []; - - return { + const result: TestCompilerHost = { trace: s => trace.push(s), getTrace: () => trace, - getSourceFile(fileName): SourceFile { - return files.get(fileName)!; - }, - getDefaultLibFileName(): string { - return "lib.d.ts"; - }, + getSourceFile: fileName => files.get(fileName), + getDefaultLibFileName: () => "lib.d.ts", writeFile: notImplemented, - getCurrentDirectory(): string { - return ""; - }, - getDirectories(): string[] { - return []; - }, - getCanonicalFileName(fileName): string { - return sys && sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - }, - useCaseSensitiveFileNames(): boolean { - return sys && sys.useCaseSensitiveFileNames; - }, - getNewLine(): string { - return sys ? sys.newLine : newLine; - }, + getCurrentDirectory: () => "", + getDirectories: () => [], + getCanonicalFileName, + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, + getNewLine: () => sys ? sys.newLine : newLine, fileExists: fileName => files.has(fileName), readFile: fileName => { const file = files.get(fileName); return file && file.text; }, }; + if (useGetSourceFileByPath) { + const filesByPath = mapEntries(files, (fileName, file) => [toPath(fileName, "", getCanonicalFileName), file]); + result.getSourceFileByPath = (_fileName, path) => filesByPath.get(path); + } + return result; } - export function newProgram(texts: NamedSourceText[], rootNames: string[], options: CompilerOptions): ProgramWithSourceTexts { - const host = createTestCompilerHost(texts, options.target!); + export function newProgram(texts: NamedSourceText[], rootNames: string[], options: CompilerOptions, useGetSourceFileByPath?: boolean): ProgramWithSourceTexts { + const host = createTestCompilerHost(texts, options.target!, /*oldProgram*/ undefined, useGetSourceFileByPath); const program = createProgram(rootNames, options, host); program.sourceTexts = texts; program.host = host; return program; } - export function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: ReadonlyArray, options: CompilerOptions, updater: (files: NamedSourceText[]) => void, newTexts?: NamedSourceText[]) { + export function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: ReadonlyArray, options: CompilerOptions, updater: (files: NamedSourceText[]) => void, newTexts?: NamedSourceText[], useGetSourceFileByPath?: boolean) { if (!newTexts) { newTexts = oldProgram.sourceTexts!.slice(0); } updater(newTexts); - const host = createTestCompilerHost(newTexts, options.target!, oldProgram); + const host = createTestCompilerHost(newTexts, options.target!, oldProgram, useGetSourceFileByPath); const program = createProgram(rootNames, options, host, oldProgram); program.sourceTexts = newTexts; program.host = host; @@ -305,10 +297,10 @@ namespace ts { assert.equal(program1.structureIsReused, StructureIsReused.Not); }); - it("fails if rootdir changes", () => { + it("succeeds if rootdir changes", () => { const program1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/b" }); updateProgram(program1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, noop); - assert.equal(program1.structureIsReused, StructureIsReused.Not); + assert.equal(program1.structureIsReused, StructureIsReused.Completely); }); it("fails if config path changes", () => { @@ -809,7 +801,7 @@ namespace ts { const root = "/a.ts"; const compilerOptions = { target, moduleResolution: ModuleResolutionKind.NodeJs }; - function createRedirectProgram(options?: { bText: string, bVersion: string }): ProgramWithSourceTexts { + function createRedirectProgram(useGetSourceFileByPath: boolean, options?: { bText: string, bVersion: string }): ProgramWithSourceTexts { const files: NamedSourceText[] = [ { name: "/node_modules/a/index.d.ts", @@ -841,55 +833,64 @@ namespace ts { }, ]; - return newProgram(files, [root], compilerOptions); + return newProgram(files, [root], compilerOptions, useGetSourceFileByPath); } - function updateRedirectProgram(program: ProgramWithSourceTexts, updater: (files: NamedSourceText[]) => void): ProgramWithSourceTexts { - return updateProgram(program, [root], compilerOptions, updater); + function updateRedirectProgram(program: ProgramWithSourceTexts, updater: (files: NamedSourceText[]) => void, useGetSourceFileByPath: boolean): ProgramWithSourceTexts { + return updateProgram(program, [root], compilerOptions, updater, /*newTexts*/ undefined, useGetSourceFileByPath); } - it("No changes -> redirect not broken", () => { - const program1 = createRedirectProgram(); + function verifyRedirects(useGetSourceFileByPath: boolean) { + it("No changes -> redirect not broken", () => { + const program1 = createRedirectProgram(useGetSourceFileByPath); - const program2 = updateRedirectProgram(program1, files => { - updateProgramText(files, root, "const x = 1;"); + const program2 = updateRedirectProgram(program1, files => { + updateProgramText(files, root, "const x = 1;"); + }, useGetSourceFileByPath); + assert.equal(program1.structureIsReused, StructureIsReused.Completely); + assert.lengthOf(program2.getSemanticDiagnostics(), 0); }); - assert.equal(program1.structureIsReused, StructureIsReused.Completely); - assert.lengthOf(program2.getSemanticDiagnostics(), 0); + + it("Target changes -> redirect broken", () => { + const program1 = createRedirectProgram(useGetSourceFileByPath); + assert.lengthOf(program1.getSemanticDiagnostics(), 0); + + const program2 = updateRedirectProgram(program1, files => { + updateProgramText(files, axIndex, "export default class X { private x: number; private y: number; }"); + updateProgramText(files, axPackage, JSON.stringify('{ name: "x", version: "1.2.4" }')); + }, useGetSourceFileByPath); + assert.equal(program1.structureIsReused, StructureIsReused.Not); + assert.lengthOf(program2.getSemanticDiagnostics(), 1); + }); + + it("Underlying changes -> redirect broken", () => { + const program1 = createRedirectProgram(useGetSourceFileByPath); + + const program2 = updateRedirectProgram(program1, files => { + updateProgramText(files, bxIndex, "export default class X { private x: number; private y: number; }"); + updateProgramText(files, bxPackage, JSON.stringify({ name: "x", version: "1.2.4" })); + }, useGetSourceFileByPath); + assert.equal(program1.structureIsReused, StructureIsReused.Not); + assert.lengthOf(program2.getSemanticDiagnostics(), 1); + }); + + it("Previously duplicate packages -> program structure not reused", () => { + const program1 = createRedirectProgram(useGetSourceFileByPath, { bVersion: "1.2.4", bText: "export = class X { private x: number; }" }); + + const program2 = updateRedirectProgram(program1, files => { + updateProgramText(files, bxIndex, "export default class X { private x: number; }"); + updateProgramText(files, bxPackage, JSON.stringify({ name: "x", version: "1.2.3" })); + }, useGetSourceFileByPath); + assert.equal(program1.structureIsReused, StructureIsReused.Not); + assert.deepEqual(program2.getSemanticDiagnostics(), []); + }); + } + + describe("when host implements getSourceFile", () => { + verifyRedirects(/*useGetSourceFileByPath*/ false); }); - - it("Target changes -> redirect broken", () => { - const program1 = createRedirectProgram(); - assert.lengthOf(program1.getSemanticDiagnostics(), 0); - - const program2 = updateRedirectProgram(program1, files => { - updateProgramText(files, axIndex, "export default class X { private x: number; private y: number; }"); - updateProgramText(files, axPackage, JSON.stringify('{ name: "x", version: "1.2.4" }')); - }); - assert.equal(program1.structureIsReused, StructureIsReused.Not); - assert.lengthOf(program2.getSemanticDiagnostics(), 1); - }); - - it("Underlying changes -> redirect broken", () => { - const program1 = createRedirectProgram(); - - const program2 = updateRedirectProgram(program1, files => { - updateProgramText(files, bxIndex, "export default class X { private x: number; private y: number; }"); - updateProgramText(files, bxPackage, JSON.stringify({ name: "x", version: "1.2.4" })); - }); - assert.equal(program1.structureIsReused, StructureIsReused.Not); - assert.lengthOf(program2.getSemanticDiagnostics(), 1); - }); - - it("Previously duplicate packages -> program structure not reused", () => { - const program1 = createRedirectProgram({ bVersion: "1.2.4", bText: "export = class X { private x: number; }" }); - - const program2 = updateRedirectProgram(program1, files => { - updateProgramText(files, bxIndex, "export default class X { private x: number; }"); - updateProgramText(files, bxPackage, JSON.stringify({ name: "x", version: "1.2.3" })); - }); - assert.equal(program1.structureIsReused, StructureIsReused.Not); - assert.deepEqual(program2.getSemanticDiagnostics(), []); + describe("when host implements getSourceFileByPath", () => { + verifyRedirects(/*useGetSourceFileByPath*/ true); }); }); }); @@ -914,7 +915,8 @@ namespace ts { program, newRootFileNames, newOptions, path => program.getSourceFileByPath(path)!.version, /*fileExists*/ returnFalse, /*hasInvalidatedResolution*/ returnFalse, - /*hasChangedAutomaticTypeDirectiveNames*/ false + /*hasChangedAutomaticTypeDirectiveNames*/ false, + /*projectReferences*/ undefined ); assert.isTrue(actual); } diff --git a/src/testRunner/unittests/semver.ts b/src/testRunner/unittests/semver.ts new file mode 100644 index 00000000000..357a24307ca --- /dev/null +++ b/src/testRunner/unittests/semver.ts @@ -0,0 +1,228 @@ +namespace ts { + import theory = utils.theory; + describe("semver", () => { + describe("Version", () => { + function assertVersion(version: Version, [major, minor, patch, prerelease, build]: [number, number, number, string[]?, string[]?]) { + assert.strictEqual(version.major, major); + assert.strictEqual(version.minor, minor); + assert.strictEqual(version.patch, patch); + assert.deepEqual(version.prerelease, prerelease || emptyArray); + assert.deepEqual(version.build, build || emptyArray); + } + describe("new", () => { + it("text", () => { + assertVersion(new Version("1.2.3-pre.4+build.5"), [1, 2, 3, ["pre", "4"], ["build", "5"]]); + }); + it("parts", () => { + assertVersion(new Version(1, 2, 3, "pre.4", "build.5"), [1, 2, 3, ["pre", "4"], ["build", "5"]]); + assertVersion(new Version(1, 2, 3), [1, 2, 3]); + assertVersion(new Version(1, 2), [1, 2, 0]); + assertVersion(new Version(1), [1, 0, 0]); + }); + }); + it("toString", () => { + assert.strictEqual(new Version(1, 2, 3, "pre.4", "build.5").toString(), "1.2.3-pre.4+build.5"); + assert.strictEqual(new Version(1, 2, 3, "pre.4").toString(), "1.2.3-pre.4"); + assert.strictEqual(new Version(1, 2, 3, /*prerelease*/ undefined, "build.5").toString(), "1.2.3+build.5"); + assert.strictEqual(new Version(1, 2, 3).toString(), "1.2.3"); + assert.strictEqual(new Version(1, 2).toString(), "1.2.0"); + assert.strictEqual(new Version(1).toString(), "1.0.0"); + }); + it("compareTo", () => { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + assert.strictEqual(new Version("1.0.0").compareTo(new Version("2.0.0")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.1.0")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.0.1")), Comparison.LessThan); + assert.strictEqual(new Version("2.0.0").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.1.0").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.1").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.0.0")), Comparison.EqualTo); + + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower + // > precedence than a normal version. + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.0.0-pre")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.1-pre").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-pre").compareTo(new Version("1.0.0")), Comparison.LessThan); + + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-1")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-1").compareTo(new Version("1.0.0-0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-2").compareTo(new Version("1.0.0-10")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-10").compareTo(new Version("1.0.0-2")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-0")), Comparison.EqualTo); + + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + assert.strictEqual(new Version("1.0.0-a").compareTo(new Version("1.0.0-b")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-a-2").compareTo(new Version("1.0.0-a-10")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-b").compareTo(new Version("1.0.0-a")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-a").compareTo(new Version("1.0.0-a")), Comparison.EqualTo); + assert.strictEqual(new Version("1.0.0-A").compareTo(new Version("1.0.0-a")), Comparison.LessThan); + + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-alpha")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-alpha").compareTo(new Version("1.0.0-0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-0")), Comparison.EqualTo); + assert.strictEqual(new Version("1.0.0-alpha").compareTo(new Version("1.0.0-alpha")), Comparison.EqualTo); + + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + assert.strictEqual(new Version("1.0.0-alpha").compareTo(new Version("1.0.0-alpha.0")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-alpha.0").compareTo(new Version("1.0.0-alpha")), Comparison.GreaterThan); + + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + assert.strictEqual(new Version("1.0.0-a.0.b.1").compareTo(new Version("1.0.0-a.0.b.2")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-a.0.b.1").compareTo(new Version("1.0.0-b.0.a.1")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-a.0.b.2").compareTo(new Version("1.0.0-a.0.b.1")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-b.0.a.1").compareTo(new Version("1.0.0-a.0.b.1")), Comparison.GreaterThan); + + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + assert.strictEqual(new Version("1.0.0+build").compareTo(new Version("1.0.0")), Comparison.EqualTo); + }); + it("increment", () => { + assertVersion(new Version(1, 2, 3, "pre.4", "build.5").increment("major"), [2, 0, 0]); + assertVersion(new Version(1, 2, 3, "pre.4", "build.5").increment("minor"), [1, 3, 0]); + assertVersion(new Version(1, 2, 3, "pre.4", "build.5").increment("patch"), [1, 2, 4]); + }); + }); + describe("VersionRange", () => { + function assertRange(rangeText: string, versionText: string, inRange = true) { + const range = new VersionRange(rangeText); + const version = new Version(versionText); + assert.strictEqual(range.test(version), inRange, `Expected version '${version}' ${inRange ? `to be` : `to not be`} in range '${rangeText}' (${range})`); + } + theory("comparators", assertRange, [ + ["", "1.0.0"], + ["*", "1.0.0"], + ["1", "1.0.0"], + ["1", "2.0.0", false], + ["1.0", "1.0.0"], + ["1.0", "1.1.0", false], + ["1.0.0", "1.0.0"], + ["1.0.0", "1.0.1", false], + ["1.*", "1.0.0"], + ["1.*", "2.0.0", false], + ["1.x", "1.0.0"], + ["1.x", "2.0.0", false], + ["=1", "1.0.0"], + ["=1", "1.1.0"], + ["=1", "1.0.1"], + ["=1.0", "1.0.0"], + ["=1.0", "1.0.1"], + ["=1.0.0", "1.0.0"], + ["=*", "0.0.0"], + ["=*", "1.0.0"], + [">1", "2"], + [">1.0", "1.1"], + [">1.0.0", "1.0.1"], + [">1.0.0", "1.0.1-pre"], + [">*", "0.0.0", false], + [">*", "1.0.0", false], + [">=1", "1.0.0"], + [">=1.0", "1.0.0"], + [">=1.0.0", "1.0.0"], + [">=1.0.0", "1.0.1-pre"], + [">=*", "0.0.0"], + [">=*", "1.0.0"], + ["<2", "1.0.0"], + ["<2.1", "2.0.0"], + ["<2.0.1", "2.0.0"], + ["<2.0.0", "2.0.0-pre"], + ["<*", "0.0.0", false], + ["<*", "1.0.0", false], + ["<=2", "2.0.0"], + ["<=2.1", "2.1.0"], + ["<=2.0.1", "2.0.1"], + ["<=*", "0.0.0"], + ["<=*", "1.0.0"], + ]); + theory("conjunctions", assertRange, [ + [">1.0.0 <2.0.0", "1.0.1"], + [">1.0.0 <2.0.0", "2.0.0", false], + [">1.0.0 <2.0.0", "1.0.0", false], + [">1 >2", "3.0.0"], + ]); + theory("disjunctions", assertRange, [ + [">=1.0.0 <2.0.0 || >=3.0.0 <4.0.0", "1.0.0"], + [">=1.0.0 <2.0.0 || >=3.0.0 <4.0.0", "2.0.0", false], + [">=1.0.0 <2.0.0 || >=3.0.0 <4.0.0", "3.0.0"], + ]); + theory("hyphen", assertRange, [ + ["1.0.0 - 2.0.0", "1.0.0"], + ["1.0.0 - 2.0.0", "2.0.0"], + ["1.0.0 - 2.0.0", "3.0.0", false], + ]); + theory("tilde", assertRange, [ + ["~0", "0.0.0"], + ["~0", "0.1.0"], + ["~0", "0.1.2"], + ["~0", "0.1.9"], + ["~0", "1.0.0", false], + ["~0.1", "0.1.0"], + ["~0.1", "0.1.2"], + ["~0.1", "0.1.9"], + ["~0.1", "0.2.0", false], + ["~0.1.2", "0.1.2"], + ["~0.1.2", "0.1.9"], + ["~0.1.2", "0.2.0", false], + ["~1", "1.0.0"], + ["~1", "1.2.0"], + ["~1", "1.2.3"], + ["~1", "1.2.0"], + ["~1", "1.2.3"], + ["~1", "0.0.0", false], + ["~1", "2.0.0", false], + ["~1.2", "1.2.0"], + ["~1.2", "1.2.3"], + ["~1.2", "1.1.0", false], + ["~1.2", "1.3.0", false], + ["~1.2.3", "1.2.3"], + ["~1.2.3", "1.2.9"], + ["~1.2.3", "1.1.0", false], + ["~1.2.3", "1.3.0", false], + ]); + theory("caret", assertRange, [ + ["^0", "0.0.0"], + ["^0", "0.1.0"], + ["^0", "0.9.0"], + ["^0", "0.1.2"], + ["^0", "0.1.9"], + ["^0", "1.0.0", false], + ["^0.1", "0.1.0"], + ["^0.1", "0.1.2"], + ["^0.1", "0.1.9"], + ["^0.1.2", "0.1.2"], + ["^0.1.2", "0.1.9"], + ["^0.1.2", "0.0.0", false], + ["^0.1.2", "0.2.0", false], + ["^0.1.2", "1.0.0", false], + ["^1", "1.0.0"], + ["^1", "1.2.0"], + ["^1", "1.2.3"], + ["^1", "1.9.0"], + ["^1", "0.0.0", false], + ["^1", "2.0.0", false], + ["^1.2", "1.2.0"], + ["^1.2", "1.2.3"], + ["^1.2", "1.9.0"], + ["^1.2", "1.1.0", false], + ["^1.2", "2.0.0", false], + ["^1.2.3", "1.2.3"], + ["^1.2.3", "1.9.0"], + ["^1.2.3", "1.2.2", false], + ["^1.2.3", "2.0.0", false], + ]); + }); + }); +} \ No newline at end of file diff --git a/src/testRunner/unittests/session.ts b/src/testRunner/unittests/session.ts index b3b2cf6ce22..ac5d8093e31 100644 --- a/src/testRunner/unittests/session.ts +++ b/src/testRunner/unittests/session.ts @@ -502,7 +502,7 @@ namespace ts.server { typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, - logger: projectSystem.nullLogger, + logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler(this.customHandler, () => { @@ -570,7 +570,7 @@ namespace ts.server { typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, - logger: projectSystem.nullLogger, + logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler("echo", (req: protocol.Request) => ({ diff --git a/src/testRunner/unittests/textChanges.ts b/src/testRunner/unittests/textChanges.ts index 699f668b552..164073207b3 100644 --- a/src/testRunner/unittests/textChanges.ts +++ b/src/testRunner/unittests/textChanges.ts @@ -20,7 +20,7 @@ namespace ts { const newLineCharacter = getNewLineCharacter(printerOptions); function getRuleProvider(placeOpenBraceOnNewLineForFunctions: boolean): formatting.FormatContext { - return formatting.getFormatContext(placeOpenBraceOnNewLineForFunctions ? { ...testFormatOptions, placeOpenBraceOnNewLineForFunctions: true } : testFormatOptions); + return formatting.getFormatContext(placeOpenBraceOnNewLineForFunctions ? { ...testFormatSettings, placeOpenBraceOnNewLineForFunctions: true } : testFormatSettings); } // validate that positions that were recovered from the printed text actually match positions that will be created if the same text is parsed. diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index ea99ee92457..dca77505b80 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -23,6 +23,42 @@ namespace ts { assert(fs.existsSync(output), `Expect file ${output} to exist`); } }); + + it("builds correctly when outDir is specified", () => { + const fs = projFs.shadow(); + fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({ + compilerOptions: { composite: true, declaration: true, sourceMap: true, outDir: "outDir" }, + references: [{ path: "../core" }] + })); + + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], {}); + builder.buildAllProjects(); + host.assertDiagnosticMessages(/*empty*/); + const expectedOutputs = allExpectedOutputs.map(f => f.replace("/logic/", "/logic/outDir/")); + // Check for outputs. Not an exhaustive list + for (const output of expectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + }); + + it("builds correctly when declarationDir is specified", () => { + const fs = projFs.shadow(); + fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({ + compilerOptions: { composite: true, declaration: true, sourceMap: true, declarationDir: "out/decls" }, + references: [{ path: "../core" }] + })); + + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], {}); + builder.buildAllProjects(); + host.assertDiagnosticMessages(/*empty*/); + const expectedOutputs = allExpectedOutputs.map(f => f.replace("/logic/index.d.ts", "/logic/out/decls/index.d.ts")); + // Check for outputs. Not an exhaustive list + for (const output of expectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + }); }); describe("tsbuild - dry builds", () => { @@ -199,7 +235,7 @@ namespace ts { tick(); touch(fs, "/src/logic/index.ts"); // Because we haven't reset the build context, the builder should assume there's nothing to do right now - const status = builder.getUpToDateStatusOfFile(builder.resolveProjectName("/src/logic")!); + const status = builder.getUpToDateStatusOfFile(builder.resolveProjectName("/src/logic")); assert.equal(status.type, UpToDateStatusType.UpToDate, "Project should be assumed to be up-to-date"); // Rebuild this project @@ -210,10 +246,26 @@ namespace ts { assert.equal(fs.statSync("/src/logic/index.js").mtimeMs, time(), "JS file should have been rebuilt"); assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should *not* have been rebuilt"); + // Does not build tests or core because there is no change in declaration file + tick(); + builder.buildInvalidatedProject(); + assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should have been rebuilt"); + assert.isBelow(fs.statSync("/src/core/index.js").mtimeMs, time(), "Upstream JS file should not have been rebuilt"); + + // Rebuild this project + tick(); + fs.writeFileSync("/src/logic/index.ts", `${fs.readFileSync("/src/logic/index.ts")} +export class cNew {}`); + builder.invalidateProject("/src/logic"); + builder.buildInvalidatedProject(); + // The file should be updated + assert.equal(fs.statSync("/src/logic/index.js").mtimeMs, time(), "JS file should have been rebuilt"); + assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should *not* have been rebuilt"); + // Build downstream projects should update 'tests', but not 'core' tick(); builder.buildInvalidatedProject(); - assert.equal(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should have been rebuilt"); + assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should have been rebuilt"); assert.isBelow(fs.statSync("/src/core/index.js").mtimeMs, time(), "Upstream JS file should not have been rebuilt"); }); }); @@ -224,6 +276,10 @@ namespace ts { function verifyProjectWithResolveJsonModule(configFile: string, ...expectedDiagnosticMessages: DiagnosticMessage[]) { const fs = projFs.shadow(); + verifyProjectWithResolveJsonModuleWithFs(fs, configFile, allExpectedOutputs, ...expectedDiagnosticMessages); + } + + function verifyProjectWithResolveJsonModuleWithFs(fs: vfs.FileSystem, configFile: string, allExpectedOutputs: ReadonlyArray, ...expectedDiagnosticMessages: DiagnosticMessage[]) { const host = new fakes.SolutionBuilderHost(fs); const builder = createSolutionBuilder(host, [configFile], { dry: false, force: false, verbose: false }); builder.buildAllProjects(); @@ -240,6 +296,21 @@ namespace ts { verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withInclude.json", Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern); }); + it("with resolveJsonModule and include of *.json along with other include", () => { + verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withIncludeOfJson.json"); + }); + + it("with resolveJsonModule and include of *.json along with other include and file name matches ts file", () => { + const fs = projFs.shadow(); + fs.rimrafSync("/src/tests/src/hello.json"); + fs.writeFileSync("/src/tests/src/index.json", JSON.stringify({ hello: "world" })); + fs.writeFileSync("/src/tests/src/index.ts", `import hello from "./index.json" + +export default hello.hello`); + const allExpectedOutputs = ["/src/tests/dist/src/index.js", "/src/tests/dist/src/index.d.ts", "/src/tests/dist/src/index.json"]; + verifyProjectWithResolveJsonModuleWithFs(fs, "/src/tests/tsconfig_withIncludeOfJson.json", allExpectedOutputs); + }); + it("with resolveJsonModule and files containing json file", () => { verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withFiles.json"); }); @@ -248,6 +319,84 @@ namespace ts { verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withIncludeAndFiles.json"); }); }); + + describe("tsbuild - lists files", () => { + it("listFiles", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], { listFiles: true }); + builder.buildAllProjects(); + assert.deepEqual(host.traces, [ + ...getLibs(), + "/src/core/anotherModule.ts", + "/src/core/index.ts", + "/src/core/some_decl.d.ts", + ...getLibs(), + ...getCoreOutputs(), + "/src/logic/index.ts", + ...getLibs(), + ...getCoreOutputs(), + "/src/logic/index.d.ts", + "/src/tests/index.ts" + ]); + + function getLibs() { + return [ + "/lib/lib.d.ts", + "/lib/lib.es5.d.ts", + "/lib/lib.dom.d.ts", + "/lib/lib.webworker.importscripts.d.ts", + "/lib/lib.scripthost.d.ts" + ]; + } + + function getCoreOutputs() { + return [ + "/src/core/index.d.ts", + "/src/core/anotherModule.d.ts" + ]; + } + }); + + it("listEmittedFiles", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], { listEmittedFiles: true }); + builder.buildAllProjects(); + assert.deepEqual(host.traces, [ + "TSFILE: /src/core/anotherModule.js", + "TSFILE: /src/core/anotherModule.d.ts", + "TSFILE: /src/core/anotherModule.d.ts.map", + "TSFILE: /src/core/index.js", + "TSFILE: /src/core/index.d.ts", + "TSFILE: /src/core/index.d.ts.map", + "TSFILE: /src/logic/index.js", + "TSFILE: /src/logic/index.js.map", + "TSFILE: /src/logic/index.d.ts", + "TSFILE: /src/tests/index.js", + "TSFILE: /src/tests/index.d.ts", + ]); + }); + }); + + describe("tsbuild - with rootDir of project reference in parentDirectory", () => { + const projFs = loadProjectFromDisk("tests/projects/projectReferenceWithRootDirInParent"); + const allExpectedOutputs = [ + "/src/dist/other/other.js", "/src/dist/other/other.d.ts", + "/src/dist/main/a.js", "/src/dist/main/a.d.ts", + "/src/dist/main/b.js", "/src/dist/main/b.d.ts" + ]; + it("verify that it builds correctly", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/src/main", "/src/src/other"], {}); + builder.buildAllProjects(); + host.assertDiagnosticMessages(/*empty*/); + for (const output of allExpectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + }); + }); } export namespace OutFile { @@ -292,6 +441,48 @@ namespace ts { }); } + export namespace EmptyFiles { + const projFs = loadProjectFromDisk("tests/projects/empty-files"); + + const allExpectedOutputs = [ + "/src/core/index.js", + "/src/core/index.d.ts", + "/src/core/index.d.ts.map", + ]; + + describe("tsbuild - empty files option in tsconfig", () => { + it("has empty files diagnostic when files is empty and no references are provided", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/no-references"], { dry: false, force: false, verbose: false }); + + host.clearDiagnostics(); + builder.buildAllProjects(); + host.assertDiagnosticMessages(Diagnostics.The_files_list_in_config_file_0_is_empty); + + // Check for outputs to not be written. + for (const output of allExpectedOutputs) { + assert(!fs.existsSync(output), `Expect file ${output} to not exist`); + } + }); + + it("does not have empty files diagnostic when files is empty and references are provided", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/with-references"], { dry: false, force: false, verbose: false }); + + host.clearDiagnostics(); + builder.buildAllProjects(); + host.assertDiagnosticMessages(/*empty*/); + + // Check for outputs to be written. + for (const output of allExpectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + }); + }); + } + describe("tsbuild - graph-ordering", () => { let host: fakes.SolutionBuilderHost | undefined; const deps: [string, string][] = [ @@ -335,7 +526,6 @@ namespace ts { const projFileNames = rootNames.map(getProjectFileName); const graph = builder.getBuildGraph(projFileNames); - if (graph === undefined) throw new Error("Graph shouldn't be undefined"); assert.sameMembers(graph.buildQueue, expectedBuildSet.map(getProjectFileName)); diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index daa1276e023..439cff15c63 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -2,7 +2,7 @@ namespace ts.tscWatch { export import libFile = TestFSWithWatch.libFile; function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { const host = createSolutionBuilderWithWatchHost(system); - return ts.createSolutionBuilder(host, rootNames, defaultOptions || { dry: false, force: false, verbose: false, watch: true }); + return ts.createSolutionBuilder(host, rootNames, defaultOptions || { watch: true }); } function createSolutionBuilderWithWatch(host: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { @@ -26,8 +26,16 @@ namespace ts.tscWatch { type SubProjectFiles = [ReadonlyFile, ReadonlyFile] | [ReadonlyFile, ReadonlyFile, ReadonlyFile, ReadonlyFile]; const root = Harness.IO.getWorkspaceRoot(); + function projectPath(subProject: SubProject) { + return `${projectsLocation}/${project}/${subProject}`; + } + function projectFilePath(subProject: SubProject, baseFileName: string) { - return `${projectsLocation}/${project}/${subProject}/${baseFileName.toLowerCase()}`; + return `${projectPath(subProject)}/${baseFileName.toLowerCase()}`; + } + + function projectFileName(subProject: SubProject, baseFileName: string) { + return `${projectPath(subProject)}/${baseFileName}`; } function projectFile(subProject: SubProject, baseFileName: string): File { @@ -58,13 +66,17 @@ namespace ts.tscWatch { return getOutputFileNames(subProject, baseFileNameWithoutExtension).map(f => [f, host.getModifiedTime(f)] as OutputFileStamp); } - function getOutputFileStamps(host: WatchedSystem): OutputFileStamp[] { - return [ + function getOutputFileStamps(host: WatchedSystem, additionalFiles?: ReadonlyArray<[SubProject, string]>): OutputFileStamp[] { + const result = [ ...getOutputStamps(host, SubProject.core, "anotherModule"), ...getOutputStamps(host, SubProject.core, "index"), ...getOutputStamps(host, SubProject.logic, "index"), ...getOutputStamps(host, SubProject.tests, "index"), ]; + if (additionalFiles) { + additionalFiles.forEach(([subProject, baseFileNameWithoutExtension]) => result.push(...getOutputStamps(host, subProject, baseFileNameWithoutExtension))); + } + return result; } function verifyChangedFiles(actualStamps: OutputFileStamp[], oldTimeStamps: OutputFileStamp[], changedFiles: string[]) { @@ -85,70 +97,451 @@ namespace ts.tscWatch { const tests = subProjectFiles(SubProject.tests); const ui = subProjectFiles(SubProject.ui); const allFiles: ReadonlyArray = [libFile, ...core, ...logic, ...tests, ...ui]; - const testProjectExpectedWatchedFiles = [core[0], core[1], core[2], ...logic, ...tests].map(f => f.path); + const testProjectExpectedWatchedFiles = [core[0], core[1], core[2]!, ...logic, ...tests].map(f => f.path); // tslint:disable-line no-unnecessary-type-assertion (TODO: type assertion should be necessary) + const testProjectExpectedWatchedDirectoriesRecursive = [projectPath(SubProject.core), projectPath(SubProject.logic)]; - function createSolutionInWatchMode() { + function createSolutionInWatchMode(allFiles: ReadonlyArray, defaultOptions?: BuildOptions, disableConsoleClears?: boolean) { const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); - createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); - checkWatchedFiles(host, testProjectExpectedWatchedFiles); - checkWatchedDirectories(host, emptyArray, /*recursive*/ false); - checkWatchedDirectories(host, emptyArray, /*recursive*/ true); // TODO: #26524 - checkOutputErrorsInitial(host, emptyArray); + createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`], defaultOptions); + verifyWatches(host); + checkOutputErrorsInitial(host, emptyArray, disableConsoleClears); const outputFileStamps = getOutputFileStamps(host); for (const stamp of outputFileStamps) { assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); } return host; } + + function verifyWatches(host: WatchedSystem) { + checkWatchedFiles(host, testProjectExpectedWatchedFiles); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, testProjectExpectedWatchedDirectoriesRecursive, /*recursive*/ true); + } + it("creates solution in watch mode", () => { - createSolutionInWatchMode(); + createSolutionInWatchMode(allFiles); }); - it("change builds changes and reports found errors message", () => { - const host = createSolutionInWatchMode(); - verifyChange(`${core[1].content} + describe("validates the changes and watched files", () => { + const newFileWithoutExtension = "newFile"; + const newFile: File = { + path: projectFilePath(SubProject.core, `${newFileWithoutExtension}.ts`), + content: `export const newFileConst = 30;` + }; + + function verifyProjectChanges(allFiles: ReadonlyArray) { + function createSolutionInWatchModeToVerifyChanges(additionalFiles?: ReadonlyArray<[SubProject, string]>) { + const host = createSolutionInWatchMode(allFiles); + return { host, verifyChangeWithFile, verifyChangeAfterTimeout, verifyWatches }; + + function verifyChangeWithFile(fileName: string, content: string) { + const outputFileStamps = getOutputFileStamps(host, additionalFiles); + host.writeFile(fileName, content); + verifyChangeAfterTimeout(outputFileStamps); + } + + function verifyChangeAfterTimeout(outputFileStamps: OutputFileStamp[]) { + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedCore, outputFileStamps, [ + ...getOutputFileNames(SubProject.core, "anotherModule"), // This should not be written really + ...getOutputFileNames(SubProject.core, "index"), + ...(additionalFiles ? getOutputFileNames(SubProject.core, newFileWithoutExtension) : emptyArray) + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedLogic, changedCore, [ + ...getOutputFileNames(SubProject.logic, "index") // Again these need not be written + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds tests + const changedTests = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedTests, changedLogic, [ + ...getOutputFileNames(SubProject.tests, "index") // Again these need not be written + ]); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(); + } + + function verifyWatches() { + checkWatchedFiles(host, additionalFiles ? testProjectExpectedWatchedFiles.concat(newFile.path) : testProjectExpectedWatchedFiles); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, testProjectExpectedWatchedDirectoriesRecursive, /*recursive*/ true); + } + } + + it("change builds changes and reports found errors message", () => { + const { host, verifyChangeWithFile, verifyChangeAfterTimeout } = createSolutionInWatchModeToVerifyChanges(); + verifyChange(`${core[1].content} export class someClass { }`); - // Another change requeues and builds it - verifyChange(core[1].content); + // Another change requeues and builds it + verifyChange(core[1].content); - // Two changes together report only single time message: File change detected. Starting incremental compilation... - const outputFileStamps = getOutputFileStamps(host); - const change1 = `${core[1].content} + // Two changes together report only single time message: File change detected. Starting incremental compilation... + const outputFileStamps = getOutputFileStamps(host); + const change1 = `${core[1].content} export class someClass { }`; - host.writeFile(core[1].path, change1); - host.writeFile(core[1].path, `${change1} + host.writeFile(core[1].path, change1); + host.writeFile(core[1].path, `${change1} export class someClass2 { }`); - verifyChangeAfterTimeout(outputFileStamps); + verifyChangeAfterTimeout(outputFileStamps); - function verifyChange(coreContent: string) { - const outputFileStamps = getOutputFileStamps(host); - host.writeFile(core[1].path, coreContent); - verifyChangeAfterTimeout(outputFileStamps); + function verifyChange(coreContent: string) { + verifyChangeWithFile(core[1].path, coreContent); + } + }); + + it("non local change does not start build of referencing projects", () => { + const host = createSolutionInWatchMode(allFiles); + const outputFileStamps = getOutputFileStamps(host); + host.writeFile(core[1].path, `${core[1].content} +function foo() { }`); + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host); + verifyChangedFiles(changedCore, outputFileStamps, [ + ...getOutputFileNames(SubProject.core, "anotherModule"), // This should not be written really + ...getOutputFileNames(SubProject.core, "index"), + ]); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(host); + }); + + it("builds when new file is added, and its subsequent updates", () => { + const additinalFiles: ReadonlyArray<[SubProject, string]> = [[SubProject.core, newFileWithoutExtension]]; + const { verifyChangeWithFile } = createSolutionInWatchModeToVerifyChanges(additinalFiles); + verifyChange(newFile.content); + + // Another change requeues and builds it + verifyChange(`${newFile.content} +export class someClass2 { }`); + + function verifyChange(newFileContent: string) { + verifyChangeWithFile(newFile.path, newFileContent); + } + }); } - function verifyChangeAfterTimeout(outputFileStamps: OutputFileStamp[]) { + describe("with simple project reference graph", () => { + verifyProjectChanges(allFiles); + }); + + describe("with circular project reference", () => { + const [coreTsconfig, ...otherCoreFiles] = core; + const circularCoreConfig: File = { + path: coreTsconfig.path, + content: JSON.stringify({ + compilerOptions: { composite: true, declaration: true }, + references: [{ path: "../tests", circular: true }] + }) + }; + verifyProjectChanges([libFile, circularCoreConfig, ...otherCoreFiles, ...logic, ...tests]); + }); + }); + + it("watches config files that are not present", () => { + const allFiles = [libFile, ...core, logic[1], ...tests]; + const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); + createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); + checkWatchedFiles(host, [core[0], core[1], core[2]!, logic[0], ...tests].map(f => f.path)); // tslint:disable-line no-unnecessary-type-assertion (TODO: type assertion should be necessary) + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, [projectPath(SubProject.core)], /*recursive*/ true); + checkOutputErrorsInitial(host, [ + createCompilerDiagnostic(Diagnostics.File_0_not_found, logic[0].path) + ]); + for (const f of [ + ...getOutputFileNames(SubProject.core, "anotherModule"), + ...getOutputFileNames(SubProject.core, "index") + ]) { + assert.isTrue(host.fileExists(f), `${f} expected to be present`); + } + for (const f of [ + ...getOutputFileNames(SubProject.logic, "index"), + ...getOutputFileNames(SubProject.tests, "index") + ]) { + assert.isFalse(host.fileExists(f), `${f} expected to be absent`); + } + + // Create tsconfig file for logic and see that build succeeds + const initial = getOutputFileStamps(host); + host.writeFile(logic[0].path, logic[0].content); + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host); + verifyChangedFiles(changedLogic, initial, [ + ...getOutputFileNames(SubProject.logic, "index") + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds tests + const changedTests = getOutputFileStamps(host); + verifyChangedFiles(changedTests, changedLogic, [ + ...getOutputFileNames(SubProject.tests, "index") + ]); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(host); + }); + + it("when referenced using prepend, builds referencing project even for non local change", () => { + const coreTsConfig: File = { + path: core[0].path, + content: JSON.stringify({ + compilerOptions: { composite: true, declaration: true, outFile: "index.js" } + }) + }; + const coreIndex: File = { + path: core[1].path, + content: `function foo() { return 10; }` + }; + const logicTsConfig: File = { + path: logic[0].path, + content: JSON.stringify({ + compilerOptions: { composite: true, declaration: true, outFile: "index.js" }, + references: [{ path: "../core", prepend: true }] + }) + }; + const logicIndex: File = { + path: logic[1].path, + content: `function bar() { return foo() + 1 };` + }; + + const projectFiles = [coreTsConfig, coreIndex, logicTsConfig, logicIndex]; + const host = createWatchedSystem([libFile, ...projectFiles], { currentDirectory: projectsLocation }); + createSolutionBuilderWithWatch(host, [`${project}/${SubProject.logic}`]); + verifyWatches(); + checkOutputErrorsInitial(host, emptyArray); + const outputFileStamps = getOutputFileStamps(); + for (const stamp of outputFileStamps) { + assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); + } + + // Make non local change + verifyChangeInCore(`${coreIndex.content} +function myFunc() { return 10; }`); + + // Make local change to function bar + verifyChangeInCore(`${coreIndex.content} +function myFunc() { return 100; }`); + + function verifyChangeInCore(content: string) { + const outputFileStamps = getOutputFileStamps(); + host.writeFile(coreIndex.path, content); + host.checkTimeoutQueueLengthAndRun(1); // Builds core - const changedCore = getOutputFileStamps(host); + const changedCore = getOutputFileStamps(); verifyChangedFiles(changedCore, outputFileStamps, [ - ...getOutputFileNames(SubProject.core, "anotherModule"), // This should not be written really ...getOutputFileNames(SubProject.core, "index") ]); - host.checkTimeoutQueueLengthAndRun(1); // Builds tests - const changedTests = getOutputFileStamps(host); - verifyChangedFiles(changedTests, changedCore, [ - ...getOutputFileNames(SubProject.tests, "index") // Again these need not be written - ]); host.checkTimeoutQueueLengthAndRun(1); // Builds logic - const changedLogic = getOutputFileStamps(host); - verifyChangedFiles(changedLogic, changedTests, [ - ...getOutputFileNames(SubProject.logic, "index") // Again these need not be written + const changedLogic = getOutputFileStamps(); + verifyChangedFiles(changedLogic, changedCore, [ + ...getOutputFileNames(SubProject.logic, "index") ]); host.checkTimeoutQueueLength(0); checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(); + } + + function getOutputFileStamps(): OutputFileStamp[] { + const result = [ + ...getOutputStamps(host, SubProject.core, "index"), + ...getOutputStamps(host, SubProject.logic, "index"), + ]; + return result; + } + + function verifyWatches() { + checkWatchedFiles(host, projectFiles.map(f => f.path)); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, testProjectExpectedWatchedDirectoriesRecursive, /*recursive*/ true); } }); - // TODO: write tests reporting errors but that will have more involved work since file + it("when referenced project change introduces error in the down stream project and then fixes it", () => { + const subProjectLibrary = `${projectsLocation}/${project}/Library`; + const libraryTs: File = { + path: `${subProjectLibrary}/library.ts`, + content: ` +interface SomeObject +{ + message: string; +} + +export function createSomeObject(): SomeObject +{ + return { + message: "new Object" + }; +}` + }; + const libraryTsconfig: File = { + path: `${subProjectLibrary}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { composite: true } }) + }; + const subProjectApp = `${projectsLocation}/${project}/App`; + const appTs: File = { + path: `${subProjectApp}/app.ts`, + content: `import { createSomeObject } from "../Library/library"; +createSomeObject().message;` + }; + const appTsconfig: File = { + path: `${subProjectApp}/tsconfig.json`, + content: JSON.stringify({ references: [{ path: "../Library" }] }) + }; + + const files = [libFile, libraryTs, libraryTsconfig, appTs, appTsconfig]; + const host = createWatchedSystem(files, { currentDirectory: `${projectsLocation}/${project}` }); + createSolutionBuilderWithWatch(host, ["App"]); + checkOutputErrorsInitial(host, emptyArray); + + // Change message in library to message2 + host.writeFile(libraryTs.path, libraryTs.content.replace(/message/g, "message2")); + host.checkTimeoutQueueLengthAndRun(1); // Build library + host.checkTimeoutQueueLengthAndRun(1); // Build App + checkOutputErrorsIncremental(host, [ + "App/app.ts(2,20): error TS2551: Property 'message' does not exist on type 'SomeObject'. Did you mean 'message2'?\n" + ]); + + // Revert library changes + host.writeFile(libraryTs.path, libraryTs.content); + host.checkTimeoutQueueLengthAndRun(1); // Build library + host.checkTimeoutQueueLengthAndRun(1); // Build App + checkOutputErrorsIncremental(host, emptyArray); + }); + + describe("reports errors in all projects on incremental compile", () => { + function verifyIncrementalErrors(defaultBuildOptions?: BuildOptions, disabledConsoleClear?: boolean) { + const host = createSolutionInWatchMode(allFiles, defaultBuildOptions, disabledConsoleClear); + const outputFileStamps = getOutputFileStamps(host); + + host.writeFile(logic[1].path, `${logic[1].content} +let y: string = 10;`); + + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host); + verifyChangedFiles(changedLogic, outputFileStamps, emptyArray); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, [ + `sample1/logic/index.ts(8,5): error TS2322: Type '10' is not assignable to type 'string'.\n` + ], disabledConsoleClear); + + host.writeFile(core[1].path, `${core[1].content} +let x: string = 10;`); + + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host); + verifyChangedFiles(changedCore, changedLogic, emptyArray); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, [ + `sample1/core/index.ts(5,5): error TS2322: Type '10' is not assignable to type 'string'.\n`, + `sample1/logic/index.ts(8,5): error TS2322: Type '10' is not assignable to type 'string'.\n` + ], disabledConsoleClear); + } + + it("when preserveWatchOutput is not used", () => { + verifyIncrementalErrors(); + }); + + it("when preserveWatchOutput is passed on command line", () => { + verifyIncrementalErrors({ preserveWatchOutput: true, watch: true }, /*disabledConsoleClear*/ true); + }); + }); + + describe("tsc-watch works with project references", () => { + const coreIndexDts = projectFileName(SubProject.core, "index.d.ts"); + const coreAnotherModuleDts = projectFileName(SubProject.core, "anotherModule.d.ts"); + const logicIndexDts = projectFileName(SubProject.logic, "index.d.ts"); + const expectedWatchedFiles = [core[0], logic[0], ...tests, libFile].map(f => f.path).concat([coreIndexDts, coreAnotherModuleDts, logicIndexDts].map(f => f.toLowerCase())); + const expectedWatchedDirectoriesRecursive = projectSystem.getTypeRootsFromLocation(projectPath(SubProject.tests)); + + function createSolution() { + const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); + const solutionBuilder = createSolutionBuilder(host, [`${project}/${SubProject.tests}`], {}); + return { host, solutionBuilder }; + } + + function createBuiltSolution() { + const result = createSolution(); + const { host, solutionBuilder } = result; + solutionBuilder.buildAllProjects(); + const outputFileStamps = getOutputFileStamps(host); + for (const stamp of outputFileStamps) { + assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); + } + return result; + } + + function verifyWatches(host: WatchedSystem) { + checkWatchedFilesDetailed(host, expectedWatchedFiles, 1); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true); + } + + function createSolutionAndWatchMode() { + // Build the composite project + const { host, solutionBuilder } = createBuiltSolution(); + + // Build in watch mode + const watch = createWatchOfConfigFileReturningBuilder(tests[0].path, host); + checkOutputErrorsInitial(host, emptyArray); + + return { host, solutionBuilder, watch }; + } + + function verifyDependencies(watch: () => BuilderProgram, filePath: string, expected: ReadonlyArray) { + checkArray(`${filePath} dependencies`, watch().getAllDependencies(watch().getSourceFile(filePath)!), expected); + } + + describe("invoking when references are already built", () => { + it("verifies dependencies and watches", () => { + const { host, watch } = createSolutionAndWatchMode(); + + verifyWatches(host); + verifyDependencies(watch, coreIndexDts, [coreIndexDts]); + verifyDependencies(watch, coreAnotherModuleDts, [coreAnotherModuleDts]); + verifyDependencies(watch, logicIndexDts, [logicIndexDts, coreAnotherModuleDts]); + verifyDependencies(watch, tests[1].path, [tests[1].path, coreAnotherModuleDts, logicIndexDts, coreAnotherModuleDts]); + }); + + it("local edit in ts file, result in watch compilation because logic.d.ts is written", () => { + const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); + host.writeFile(logic[1].path, `${logic[1].content} +function foo() { +}`); + solutionBuilder.invalidateProject(`${project}/${SubProject.logic}`); + solutionBuilder.buildInvalidatedProject(); + + host.checkTimeoutQueueLengthAndRun(1); // not ideal, but currently because of d.ts but no new file is written + checkOutputErrorsIncremental(host, emptyArray); + checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]); + }); + + it("non local edit in ts file, rebuilds in watch compilation", () => { + const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); + host.writeFile(logic[1].path, `${logic[1].content} +export function gfoo() { +}`); + solutionBuilder.invalidateProject(logic[0].path); + solutionBuilder.buildInvalidatedProject(); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]); + }); + + it("change in project reference config file builds correctly", () => { + const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); + host.writeFile(logic[0].path, JSON.stringify({ + compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, + references: [{ path: "../core" }] + })); + solutionBuilder.invalidateProject(logic[0].path, ConfigFileProgramReloadLevel.Full); + solutionBuilder.buildInvalidatedProject(); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")]); + }); + }); + }); }); } diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index da1c4fd0d70..7678bfe0625 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -20,7 +20,14 @@ namespace ts.tscWatch { checkArray(`Program rootFileNames`, program.getRootFileNames(), expectedFiles); } - function createWatchOfConfigFile(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { + export function createWatchOfConfigFileReturningBuilder(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { + const compilerHost = createWatchCompilerHostOfConfigFile(configFileName, {}, host); + compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation; + const watch = createWatchProgram(compilerHost); + return () => watch.getCurrentProgram(); + } + + export function createWatchOfConfigFile(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { const compilerHost = createWatchCompilerHostOfConfigFile(configFileName, {}, host); compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation; const watch = createWatchProgram(compilerHost); @@ -77,7 +84,7 @@ namespace ts.tscWatch { logsBeforeWatchDiagnostic: string[] | undefined, preErrorsWatchDiagnostic: Diagnostic, logsBeforeErrors: string[] | undefined, - errors: ReadonlyArray, + errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean | undefined, ...postErrorsWatchDiagnostics: Diagnostic[] ) { @@ -96,8 +103,12 @@ namespace ts.tscWatch { assert.equal(host.screenClears.length, screenClears, "Expected number of screen clears"); host.clearOutput(); - function assertDiagnostic(diagnostic: Diagnostic) { - const expected = formatDiagnostic(diagnostic, host); + function isDiagnostic(diagnostic: Diagnostic | string): diagnostic is Diagnostic { + return !!(diagnostic as Diagnostic).messageText; + } + + function assertDiagnostic(diagnostic: Diagnostic | string) { + const expected = isDiagnostic(diagnostic) ? formatDiagnostic(diagnostic, host) : diagnostic; assert.equal(outputs[index], expected, getOutputAtFailedMessage("Diagnostic", expected)); index++; } @@ -130,13 +141,13 @@ namespace ts.tscWatch { } } - function createErrorsFoundCompilerDiagnostic(errors: ReadonlyArray) { + function createErrorsFoundCompilerDiagnostic(errors: ReadonlyArray | ReadonlyArray) { return errors.length === 1 ? createCompilerDiagnostic(Diagnostics.Found_1_error_Watching_for_file_changes) : createCompilerDiagnostic(Diagnostics.Found_0_errors_Watching_for_file_changes, errors.length); } - export function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { + export function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { checkOutputErrors( host, /*logsBeforeWatchDiagnostic*/ undefined, @@ -147,7 +158,7 @@ namespace ts.tscWatch { createErrorsFoundCompilerDiagnostic(errors)); } - export function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + export function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { checkOutputErrors( host, logsBeforeWatchDiagnostic, @@ -158,7 +169,7 @@ namespace ts.tscWatch { createErrorsFoundCompilerDiagnostic(errors)); } - function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { checkOutputErrors( host, logsBeforeWatchDiagnostic, @@ -439,6 +450,33 @@ namespace ts.tscWatch { checkOutputErrorsIncremental(host, emptyArray); }); + it("Updates diagnostics when '--noUnusedLabels' changes", () => { + const aTs: File = { path: "/a.ts", content: "label: while (1) {}" }; + const files = [libFile, aTs]; + const paths = files.map(f => f.path); + const options = (allowUnusedLabels: boolean) => `{ "compilerOptions": { "allowUnusedLabels": ${allowUnusedLabels} } }`; + const tsconfig: File = { path: "/tsconfig.json", content: options(/*allowUnusedLabels*/ true) }; + + const host = createWatchedSystem([...files, tsconfig]); + const watch = createWatchOfConfigFile(tsconfig.path, host); + + checkProgramActualFiles(watch(), paths); + checkOutputErrorsInitial(host, emptyArray); + + host.modifyFile(tsconfig.path, options(/*allowUnusedLabels*/ false)); + host.checkTimeoutQueueLengthAndRun(1); // reload the configured project + + checkProgramActualFiles(watch(), paths); + checkOutputErrorsIncremental(host, [ + getDiagnosticOfFileFromProgram(watch(), aTs.path, 0, "label".length, Diagnostics.Unused_label), + ]); + + host.modifyFile(tsconfig.path, options(/*allowUnusedLabels*/ true)); + host.checkTimeoutQueueLengthAndRun(1); // reload the configured project + checkProgramActualFiles(watch(), paths); + checkOutputErrorsIncremental(host, emptyArray); + }); + it("files explicitly excluded in config file", () => { const configFile: File = { path: "/a/b/tsconfig.json", @@ -1186,7 +1224,7 @@ namespace ts.tscWatch { host.reloadFS(files); host.runQueuedTimeoutCallbacks(); checkProgramActualFiles(watch(), files.map(file => file.path)); - checkOutputErrorsIncremental(host, []); + checkOutputErrorsIncremental(host, emptyArray); }); it("watched files when file is deleted and new file is added as part of change", () => { @@ -1318,12 +1356,10 @@ export class B path: `${currentDirectory}/a.ts`, content: `declare function foo(): null | { hello: any }; foo().hello` - }; - const compilerOptions: CompilerOptions = { }; const config: File = { path: `${currentDirectory}/tsconfig.json`, - content: JSON.stringify({ compilerOptions }) + content: JSON.stringify({ compilerOptions: {} }) }; const files = [aFile, config, libFile]; const host = createWatchedSystem(files, { currentDirectory }); @@ -1331,8 +1367,7 @@ foo().hello` checkProgramActualFiles(watch(), [aFile.path, libFile.path]); checkOutputErrorsInitial(host, emptyArray); const modifiedTimeOfAJs = host.getModifiedTime(`${currentDirectory}/a.js`); - compilerOptions.strictNullChecks = true; - host.writeFile(config.path, JSON.stringify({ compilerOptions })); + host.writeFile(config.path, JSON.stringify({ compilerOptions: { strictNullChecks: true } })); host.runQueuedTimeoutCallbacks(); const expectedStrictNullErrors = [ getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.lastIndexOf("foo()"), 5, Diagnostics.Object_is_possibly_null) @@ -1340,20 +1375,52 @@ foo().hello` checkOutputErrorsIncremental(host, expectedStrictNullErrors); // File a need not be rewritten assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); - compilerOptions.strict = true; - delete (compilerOptions.strictNullChecks); - host.writeFile(config.path, JSON.stringify({ compilerOptions })); + host.writeFile(config.path, JSON.stringify({ compilerOptions: { strict: true, alwaysStrict: false } })); // Avoid changing 'alwaysStrict' or must re-bind host.runQueuedTimeoutCallbacks(); checkOutputErrorsIncremental(host, expectedStrictNullErrors); // File a need not be rewritten assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); - delete (compilerOptions.strict); - host.writeFile(config.path, JSON.stringify({ compilerOptions })); + host.writeFile(config.path, JSON.stringify({ compilerOptions: {} })); host.runQueuedTimeoutCallbacks(); checkOutputErrorsIncremental(host, emptyArray); // File a need not be rewritten assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); }); + + it("updates errors when ambient modules of program changes", () => { + const currentDirectory = "/user/username/projects/myproject"; + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `declare module 'a' { + type foo = number; +}` + }; + const config: File = { + path: `${currentDirectory}/tsconfig.json`, + content: "{}" + }; + const files = [aFile, config, libFile]; + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfConfigFile("tsconfig.json", host); + checkProgramActualFiles(watch(), [aFile.path, libFile.path]); + checkOutputErrorsInitial(host, emptyArray); + + // Create bts with same file contents + const bTsPath = `${currentDirectory}/b.ts`; + host.writeFile(bTsPath, aFile.content); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), [aFile.path, "b.ts", libFile.path]); + checkOutputErrorsIncremental(host, [ + "a.ts(2,8): error TS2300: Duplicate identifier 'foo'.\n", + "b.ts(2,8): error TS2300: Duplicate identifier 'foo'.\n" + ]); + + // Delete bTs + host.deleteFile(bTsPath); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), [aFile.path, libFile.path]); + checkOutputErrorsIncremental(host, emptyArray); + }); }); describe("tsc-watch emit with outFile or out setting", () => { diff --git a/src/testRunner/unittests/tsconfigParsing.ts b/src/testRunner/unittests/tsconfigParsing.ts index 6ef5697046f..6909e260d2a 100644 --- a/src/testRunner/unittests/tsconfigParsing.ts +++ b/src/testRunner/unittests/tsconfigParsing.ts @@ -61,6 +61,19 @@ namespace ts { } } + function assertParseFileDiagnosticsExclusion(jsonText: string, configFileName: string, basePath: string, allFileList: string[], expectedExcludedDiagnosticCode: number) { + { + const parsed = getParsedCommandJson(jsonText, configFileName, basePath, allFileList); + assert.isTrue(parsed.errors.length >= 0); + assert.isTrue(parsed.errors.findIndex(e => e.code === expectedExcludedDiagnosticCode) === -1, `Expected error code ${expectedExcludedDiagnosticCode} to not be in ${JSON.stringify(parsed.errors)}`); + } + { + const parsed = getParsedCommandJsonNode(jsonText, configFileName, basePath, allFileList); + assert.isTrue(parsed.errors.length >= 0); + assert.isTrue(parsed.errors.findIndex(e => e.code === expectedExcludedDiagnosticCode) === -1, `Expected error code ${expectedExcludedDiagnosticCode} to not be in ${JSON.stringify(parsed.errors)}`); + } + } + it("returns empty config for file with only whitespaces", () => { assertParseResult("", { config : {} }); assertParseResult(" ", { config : {} }); @@ -280,6 +293,30 @@ namespace ts { Diagnostics.The_files_list_in_config_file_0_is_empty.code); }); + it("generates errors for empty files list when no references are provided", () => { + const content = `{ + "files": [], + "references": [] + }`; + assertParseFileDiagnostics(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + ["/apath/a.ts"], + Diagnostics.The_files_list_in_config_file_0_is_empty.code); + }); + + it("does not generate errors for empty files list when one or more references are provided", () => { + const content = `{ + "files": [], + "references": [{ "path": "/apath" }] + }`; + assertParseFileDiagnosticsExclusion(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + ["/apath/a.ts"], + Diagnostics.The_files_list_in_config_file_0_is_empty.code); + }); + it("generates errors for directory with no .ts files", () => { const content = `{ }`; diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 7114759b097..77c486f3f67 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -58,12 +58,13 @@ namespace ts.projectSystem { getLogFileName: () => undefined, }; - function createHasErrorMessageLogger() { + export function createHasErrorMessageLogger() { let hasErrorMsg = false; const { close, hasLevel, loggingEnabled, startGroup, endGroup, info, getLogFileName, perftrc } = nullLogger; const logger: server.Logger = { close, hasLevel, loggingEnabled, startGroup, endGroup, info, getLogFileName, perftrc, - msg: () => { + msg: (s, type) => { + Debug.fail(`Error: ${s}, type: ${type}`); hasErrorMsg = true; } }; @@ -85,6 +86,7 @@ namespace ts.projectSystem { isKnownTypesPackageName = notImplemented; installPackage = notImplemented; + inspectValue = notImplemented; executePendingCommands() { const actionsToRun = this.postExecActions; @@ -321,13 +323,26 @@ namespace ts.projectSystem { typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, - logger: opts.logger || nullLogger, + logger: opts.logger || createHasErrorMessageLogger().logger, canUseEvents: false }; return new TestSession({ ...sessionOptions, ...opts }); } + function createSessionWithEventTracking(host: server.ServerHost, eventName: T["eventName"], eventName2?: U["eventName"]) { + const events: (T | U)[] = []; + const session = createSession(host, { + eventHandler: e => { + if (e.eventName === eventName || (eventName2 && e.eventName === eventName2)) { + events.push(e as T | U); + } + } + }); + + return { session, events }; + } + interface CreateProjectServiceParameters { cancellationToken?: HostCancellationToken; logger?: server.Logger; @@ -358,7 +373,7 @@ namespace ts.projectSystem { } export function createProjectService(host: server.ServerHost, parameters: CreateProjectServiceParameters = {}, options?: Partial) { const cancellationToken = parameters.cancellationToken || server.nullCancellationToken; - const logger = parameters.logger || nullLogger; + const logger = parameters.logger || createHasErrorMessageLogger().logger; const useSingleInferredProject = parameters.useSingleInferredProject !== undefined ? parameters.useSingleInferredProject : false; return new TestProjectService(host, logger, cancellationToken, useSingleInferredProject, parameters.typingsInstaller!, parameters.eventHandler!, options); // TODO: GH#18217 } @@ -448,6 +463,14 @@ namespace ts.projectSystem { const toLocation = protocolToLocation(str); return { start: toLocation(span.start), end: toLocation(textSpanEnd(span)) }; } + function protocolRenameSpanFromSubstring( + str: string, + substring: string, + options?: SpanFromSubstringOptions, + prefixSuffixText?: { readonly prefixText?: string, readonly suffixText?: string }, + ): protocol.RenameTextSpan { + return { ...protocolTextSpanFromSubstring(str, substring, options), ...prefixSuffixText }; + } function textSpanFromSubstring(str: string, substring: string, options?: SpanFromSubstringOptions): TextSpan { const start = nthIndexOf(str, substring, options ? options.index : 0); Debug.assert(start !== -1); @@ -456,12 +479,15 @@ namespace ts.projectSystem { function protocolFileLocationFromSubstring(file: File, substring: string): protocol.FileLocationRequestArgs { return { file: file.path, ...protocolLocationFromSubstring(file.content, substring) }; } - function protocolFileSpanFromSubstring(file: File, substring: string, options?: SpanFromSubstringOptions) { + function protocolFileSpanFromSubstring(file: File, substring: string, options?: SpanFromSubstringOptions): protocol.FileSpan { return { file: file.path, ...protocolTextSpanFromSubstring(file.content, substring, options) }; } function documentSpanFromSubstring(file: File, substring: string, options?: SpanFromSubstringOptions): DocumentSpan { return { fileName: file.path, textSpan: textSpanFromSubstring(file.content, substring, options) }; } + function renameLocation(file: File, substring: string, options?: SpanFromSubstringOptions): RenameLocation { + return documentSpanFromSubstring(file, substring, options); + } interface SpanFromSubstringOptions { readonly index: number; } @@ -1800,6 +1826,63 @@ namespace ts.projectSystem { } }); + it("file with name constructor.js doesnt cause issue with typeAcquisition when safe type list", () => { + const file1 = { + path: "/a/b/f1.js", + content: `export let x = 5; import { s } from "s"` + }; + const constructorFile = { + path: "/a/b/constructor.js", + content: "const x = 10;" + }; + const bliss = { + path: "/a/b/bliss.js", + content: "export function is() { return true; }" + }; + const host = createServerHost([file1, libFile, constructorFile, bliss, customTypesMap]); + let request: string | undefined; + const cachePath = "/a/data"; + const typingsInstaller: server.ITypingsInstaller = { + isKnownTypesPackageName: returnFalse, + installPackage: notImplemented, + inspectValue: notImplemented, + enqueueInstallTypingsRequest: (proj, typeAcquisition, unresolvedImports) => { + assert.isUndefined(request); + request = JSON.stringify(server.createInstallTypingsRequest(proj, typeAcquisition, unresolvedImports || server.emptyArray, cachePath)); + }, + attach: noop, + onProjectClosed: noop, + globalTypingsCacheLocation: cachePath + }; + + const projectName = "project"; + const projectService = createProjectService(host, { typingsInstaller }); + projectService.openExternalProject({ projectFileName: projectName, options: {}, rootFiles: toExternalFiles([file1.path, constructorFile.path, bliss.path]) }); + assert.equal(request, JSON.stringify({ + projectName, + fileNames: [libFile.path, file1.path, constructorFile.path, bliss.path], + compilerOptions: { allowNonTsExtensions: true, noEmitForJsFiles: true }, + typeAcquisition: { include: ["blissfuljs"], exclude: [], enable: true }, + unresolvedImports: ["s"], + projectRootPath: "/", + cachePath, + kind: "discover" + })); + const response = JSON.parse(request!); + request = undefined; + projectService.updateTypingsForProject({ + kind: "action::set", + projectName: response.projectName, + typeAcquisition: response.typeAcquisition, + compilerOptions: response.compilerOptions, + typings: emptyArray, + unresolvedImports: response.unresolvedImports, + }); + + host.checkTimeoutQueueLengthAndRun(2); + assert.isUndefined(request); + }); + it("ignores files excluded by the default type list", () => { const file1 = { path: "/a/b/f1.js", @@ -2859,18 +2942,7 @@ namespace ts.projectSystem { host.getFileSize = (filePath: string) => filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); - let lastEvent!: server.ProjectLanguageServiceStateEvent; - const session = createSession(host, { - canUseEvents: true, - eventHandler: e => { - if (e.eventName === server.ConfigFileDiagEvent || e.eventName === server.ProjectsUpdatedInBackgroundEvent || e.eventName === server.ProjectInfoTelemetryEvent || e.eventName === server.OpenFileInfoTelemetryEvent || e.eventName === server.LargeFileReferencedEvent || e.eventName === server.SurveyReady) { - return; - } - assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent); - assert.equal(e.data.project.getProjectName(), config.path, "project name"); - lastEvent = e; - } - }); + const { session, events } = createSessionWithEventTracking(host, server.ProjectLanguageServiceStateEvent); session.executeCommand({ seq: 0, type: "request", @@ -2881,17 +2953,19 @@ namespace ts.projectSystem { checkNumberOfProjects(projectService, { configuredProjects: 1 }); const project = configuredProjectAt(projectService, 0); assert.isFalse(project.languageServiceEnabled, "Language service enabled"); - assert.isTrue(!!lastEvent, "should receive event"); - assert.equal(lastEvent.data.project, project, "project name"); - assert.equal(lastEvent.data.project.getProjectName(), config.path, "config path"); - assert.isFalse(lastEvent.data.languageServiceEnabled, "Language service state"); + assert.equal(events.length, 1, "should receive event"); + assert.equal(events[0].data.project, project, "project name"); + assert.equal(events[0].data.project.getProjectName(), config.path, "config path"); + assert.isFalse(events[0].data.languageServiceEnabled, "Language service state"); host.reloadFS([f1, f2, configWithExclude]); host.checkTimeoutQueueLengthAndRun(2); checkNumberOfProjects(projectService, { configuredProjects: 1 }); assert.isTrue(project.languageServiceEnabled, "Language service enabled"); - assert.equal(lastEvent.data.project, project, "project"); - assert.isTrue(lastEvent.data.languageServiceEnabled, "Language service state"); + assert.equal(events.length, 2, "should receive event"); + assert.equal(events[1].data.project, project, "project"); + assert.equal(events[1].data.project.getProjectName(), config.path, "config path"); + assert.isTrue(events[1].data.languageServiceEnabled, "Language service state"); }); it("syntactic features work even if language service is disabled", () => { @@ -2911,17 +2985,7 @@ namespace ts.projectSystem { const originalGetFileSize = host.getFileSize; host.getFileSize = (filePath: string) => filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); - let lastEvent!: server.ProjectLanguageServiceStateEvent; - const session = createSession(host, { - canUseEvents: true, - eventHandler: e => { - if (e.eventName === server.ConfigFileDiagEvent || e.eventName === server.ProjectInfoTelemetryEvent || e.eventName === server.OpenFileInfoTelemetryEvent) { - return; - } - assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent); - lastEvent = e; - } - }); + const { session, events } = createSessionWithEventTracking(host, server.ProjectLanguageServiceStateEvent); session.executeCommand({ seq: 0, type: "request", @@ -2933,9 +2997,9 @@ namespace ts.projectSystem { checkNumberOfProjects(projectService, { configuredProjects: 1 }); const project = configuredProjectAt(projectService, 0); assert.isFalse(project.languageServiceEnabled, "Language service enabled"); - assert.isTrue(!!lastEvent, "should receive event"); - assert.equal(lastEvent.data.project, project, "project name"); - assert.isFalse(lastEvent.data.languageServiceEnabled, "Language service state"); + assert.equal(events.length, 1, "should receive event"); + assert.equal(events[0].data.project, project, "project name"); + assert.isFalse(events[0].data.languageServiceEnabled, "Language service state"); const options = projectService.getFormatCodeOptions(f1.path as server.NormalizedPath); const edits = project.getLanguageService().getFormattingEditsForDocument(f1.path, options); @@ -3136,7 +3200,7 @@ namespace ts.projectSystem { const project = projectService.configuredProjects.get(configFile.path)!; assert.isDefined(project); checkProjectActualFiles(project, [file1.path, libFile.path, module1.path, module2.path, configFile.path]); - checkWatchedFiles(host, [libFile.path, module1.path, module2.path, configFile.path]); + checkWatchedFiles(host, [libFile.path, configFile.path]); checkWatchedDirectories(host, [], /*recursive*/ false); const watchedRecursiveDirectories = getTypeRootsFromLocation(root + "/a/b/src"); watchedRecursiveDirectories.push(`${root}/a/b/src/node_modules`, `${root}/a/b/node_modules`); @@ -3204,7 +3268,7 @@ namespace ts.projectSystem { { text: "number", kind: "keyword" } ], documentation: [], - tags: [] + tags: undefined, }); }); @@ -3491,7 +3555,7 @@ namespace ts.projectSystem { host.checkTimeoutQueueLength(2); // Update configured project and projects for open file checkProjectActualFiles(services.configuredProjects.get(config.path)!, filesWithFileA.map(f => f.path)); - // host.fileExists = originalFileExists; + // host.fileExists = originalFileExists; openFile(fileSubA); // This should create inferred project since fileSubA not on the disk checkProjectActualFiles(services.configuredProjects.get(config.path)!, mapDefined(filesWithFileA, f => f === fileA ? undefined : f.path)); @@ -3540,14 +3604,7 @@ namespace ts.projectSystem { }); function createSessionWithEventHandler(host: TestServerHost) { - const surveyEvents: server.SurveyReady[] = []; - const session = createSession(host, { - eventHandler: e => { - if (e.eventName === server.SurveyReady) { - surveyEvents.push(e); - } - } - }); + const { session, events: surveyEvents } = createSessionWithEventTracking(host, server.SurveyReady); return { session, verifySurveyReadyEvent }; @@ -3672,7 +3729,7 @@ namespace ts.projectSystem { path: `${projectRoot}/app1/tsconfig.json`, content: JSON.stringify({ files: ["app.ts", "../core/core.ts"], - compilerOptions: { outFile : "build/output.js" }, + compilerOptions: { outFile: "build/output.js" }, compileOnSave: true }) }; @@ -4924,7 +4981,7 @@ namespace ts.projectSystem { checkErrorMessage(session, "suggestionDiag", { file: file.path, diagnostics: [ - createDiagnostic({ line: 1, offset: 12 }, { line: 1, offset: 13 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["p"], "suggestion", /*reportsUnnecssary*/ true) + createDiagnostic({ line: 1, offset: 12 }, { line: 1, offset: 13 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["p"], "suggestion", /*reportsUnnecessary*/ true), ], }); checkCompleteEvent(session, 2, expectedSequenceId); @@ -6778,9 +6835,9 @@ namespace ts.projectSystem { fileName: "/a.1.ts", textChanges: [ { - start: { line: 0, offset: 0 }, - end: { line: 0, offset: 0 }, - newText: "export const a = 0;", + start: { line: 0, offset: 0 }, + end: { line: 0, offset: 0 }, + newText: "export const a = 0;", }, ], } @@ -7435,7 +7492,7 @@ namespace ts.projectSystem { const projectFilePaths = map(projectFiles, f => f.path); checkProjectActualFiles(project, projectFilePaths); - const filesWatched = filter(projectFilePaths, p => p !== app.path); + const filesWatched = filter(projectFilePaths, p => p !== app.path && p.indexOf("/a/b/node_modules") === -1); checkWatchedFiles(host, filesWatched); checkWatchedDirectories(host, typeRootDirectories.concat(recursiveWatchedDirectories), /*recursive*/ true); checkWatchedDirectories(host, [], /*recursive*/ false); @@ -8283,19 +8340,21 @@ namespace ts.projectSystem { const response = executeSessionRequest(session, protocol.CommandTypes.Rename, { file: aFc, ...protocolLocationFromSubstring(cFile.content, "C") }); assert.equal(aFile.content, bFile.content); - const abLocs: protocol.TextSpan[] = [ - protocolTextSpanFromSubstring(aFile.content, "C"), - protocolTextSpanFromSubstring(aFile.content, "C", { index: 1 }), + const abLocs: protocol.RenameTextSpan[] = [ + protocolRenameSpanFromSubstring(aFile.content, "C"), + protocolRenameSpanFromSubstring(aFile.content, "C", { index: 1 }), ]; - const cLocs: protocol.TextSpan[] = [protocolTextSpanFromSubstring(cFile.content, "C")]; + const span = protocolRenameSpanFromSubstring(cFile.content, "C"); + const cLocs: protocol.RenameTextSpan[] = [span]; assert.deepEqual(response, { info: { canRename: true, displayName: "C", + fileToRename: undefined, fullDisplayName: '"/users/username/projects/a/c/fc".C', kind: ScriptElementKind.constElement, kindModifiers: ScriptElementKindModifier.exportedModifier, - localizedErrorMessage: undefined, + triggerSpan: protocolTextSpanFromSubstring(cFile.content, "C"), }, locs: [ { file: aFc, locs: cLocs }, @@ -8658,9 +8717,20 @@ new C();` } function verifyWatchesWithConfigFile(host: TestServerHost, files: File[], openFile: File, extraExpectedDirectories?: ReadonlyArray) { - checkWatchedFiles(host, mapDefined(files, f => f === openFile ? undefined : f.path)); + const expectedRecursiveDirectories = arrayToSet([projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)]); + checkWatchedFiles(host, mapDefined(files, f => { + if (f === openFile) { + return undefined; + } + const indexOfNodeModules = f.path.indexOf("/node_modules/"); + if (indexOfNodeModules === -1) { + return f.path; + } + expectedRecursiveDirectories.set(f.path.substr(0, indexOfNodeModules + "/node_modules".length), true); + return undefined; + })); checkWatchedDirectories(host, [], /*recursive*/ false); - checkWatchedDirectories(host, [projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)], /*recursive*/ true); + checkWatchedDirectories(host, arrayFrom(expectedRecursiveDirectories.keys()), /*recursive*/ true); } describe("from files in same folder", () => { @@ -8862,7 +8932,7 @@ new C();` verifyTrace(resolutionTrace, expectedTrace); const currentDirectory = getDirectoryPath(file1.path); - const watchedFiles = mapDefined(files, f => f === file1 ? undefined : f.path); + const watchedFiles = mapDefined(files, f => f === file1 || f.path.indexOf("/node_modules/") !== -1 ? undefined : f.path); forEachAncestorDirectory(currentDirectory, d => { watchedFiles.push(combinePaths(d, "tsconfig.json"), combinePaths(d, "jsconfig.json")); }); @@ -9079,7 +9149,7 @@ export const x = 10;` Debug.assert(!!project.resolveModuleNames); - const edits = project.getLanguageService().getEditsForFileRename("/old.ts", "/new.ts", testFormatOptions, emptyOptions); + const edits = project.getLanguageService().getEditsForFileRename("/old.ts", "/new.ts", testFormatSettings, emptyOptions); assert.deepEqual>(edits, [{ fileName: "/user.ts", textChanges: [{ @@ -9269,14 +9339,7 @@ export const x = 10;` }; files.push(largeFile); const host = createServerHost(files); - const largeFileReferencedEvents: server.LargeFileReferencedEvent[] = []; - const session = createSession(host, { - eventHandler: e => { - if (e.eventName === server.LargeFileReferencedEvent) { - largeFileReferencedEvents.push(e); - } - } - }); + const { session, events: largeFileReferencedEvents } = createSessionWithEventTracking(host, server.LargeFileReferencedEvent); return { session, verifyLargeFile }; @@ -9336,6 +9399,159 @@ export const x = 10;` }); }); + describe("tsserverProjectSystem ProjectLoadingStart and ProjectLoadingFinish events", () => { + const projectRoot = "/user/username/projects"; + const aTs: File = { + path: `${projectRoot}/a/a.ts`, + content: "export class A { }" + }; + const configA: File = { + path: `${projectRoot}/a/tsconfig.json`, + content: "{}" + }; + const bTsPath = `${projectRoot}/b/b.ts`; + const configBPath = `${projectRoot}/b/tsconfig.json`; + const files = [libFile, aTs, configA]; + + function createSessionWithEventHandler(files: ReadonlyArray) { + const host = createServerHost(files); + + const originalReadFile = host.readFile; + host.readFile = file => { + if (file === configA.path || file === configBPath) { + assert.equal(events.length, 1, "Event for loading is sent before reading config file"); + } + return originalReadFile.call(host, file); + }; + const { session, events } = createSessionWithEventTracking(host, server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent); + const service = session.getProjectService(); + return { host, session, verifyEvent, verifyEventWithOpenTs, service, events }; + + function verifyEvent(project: server.Project, reason: string) { + assert.deepEqual(events, [ + { eventName: server.ProjectLoadingStartEvent, data: { project, reason } }, + { eventName: server.ProjectLoadingFinishEvent, data: { project } } + ]); + events.length = 0; + } + + function verifyEventWithOpenTs(file: File, configPath: string, configuredProjects: number) { + openFilesForSession([file], session); + checkNumberOfProjects(service, { configuredProjects }); + const project = service.configuredProjects.get(configPath)!; + assert.isDefined(project); + verifyEvent(project, `Creating possible configured project for ${file.path} to open`); + } + } + + it("when project is created by open file", () => { + const bTs: File = { + path: bTsPath, + content: "export class B {}" + }; + const configB: File = { + path: configBPath, + content: "{}" + }; + const { verifyEventWithOpenTs } = createSessionWithEventHandler(files.concat(bTs, configB)); + verifyEventWithOpenTs(aTs, configA.path, 1); + verifyEventWithOpenTs(bTs, configB.path, 2); + }); + + it("when change is detected in the config file", () => { + const { host, verifyEvent, verifyEventWithOpenTs, service } = createSessionWithEventHandler(files); + verifyEventWithOpenTs(aTs, configA.path, 1); + + host.writeFile(configA.path, configA.content); + host.checkTimeoutQueueLengthAndRun(2); + const project = service.configuredProjects.get(configA.path)!; + verifyEvent(project, `Change in config file detected`); + }); + + it("when opening original location project", () => { + const aDTs: File = { + path: `${projectRoot}/a/a.d.ts`, + content: `export declare class A { +} +//# sourceMappingURL=a.d.ts.map +` + }; + const aDTsMap: File = { + path: `${projectRoot}/a/a.d.ts.map`, + content: `{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["./a.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;CAAI"}` + }; + const bTs: File = { + path: bTsPath, + content: `import {A} from "../a/a"; new A();` + }; + const configB: File = { + path: configBPath, + content: JSON.stringify({ + references: [{ path: "../a" }] + }) + }; + + const { service, session, verifyEventWithOpenTs, verifyEvent } = createSessionWithEventHandler(files.concat(aDTs, aDTsMap, bTs, configB)); + verifyEventWithOpenTs(bTs, configB.path, 1); + + session.executeCommandSeq({ + command: protocol.CommandTypes.References, + arguments: { + file: bTs.path, + ...protocolLocationFromSubstring(bTs.content, "A()") + } + }); + + checkNumberOfProjects(service, { configuredProjects: 2 }); + const project = service.configuredProjects.get(configA.path)!; + assert.isDefined(project); + verifyEvent(project, `Creating project for original file: ${aTs.path} for location: ${aDTs.path}`); + }); + + describe("with external projects and config files ", () => { + const projectFileName = `${projectRoot}/a/project.csproj`; + + function createSession(lazyConfiguredProjectsFromExternalProject: boolean) { + const { session, service, verifyEvent: verifyEventWorker, events } = createSessionWithEventHandler(files); + service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } }); + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([aTs.path, configA.path]), + options: {} + }); + checkNumberOfProjects(service, { configuredProjects: 1 }); + return { session, service, verifyEvent, events }; + + function verifyEvent() { + const projectA = service.configuredProjects.get(configA.path)!; + assert.isDefined(projectA); + verifyEventWorker(projectA, `Creating configured project in external project: ${projectFileName}`); + } + } + + it("when lazyConfiguredProjectsFromExternalProject is false", () => { + const { verifyEvent } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ false); + verifyEvent(); + }); + + it("when lazyConfiguredProjectsFromExternalProject is true and file is opened", () => { + const { verifyEvent, events, session } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ true); + assert.equal(events.length, 0); + + openFilesForSession([aTs], session); + verifyEvent(); + }); + + it("when lazyConfiguredProjectsFromExternalProject is disabled", () => { + const { verifyEvent, events, service } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ true); + assert.equal(events.length, 0); + + service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject: false } }); + verifyEvent(); + }); + }); + }); + describe("tsserverProjectSystem syntax operations", () => { function navBarFull(session: TestSession, file: File) { return JSON.stringify(session.executeCommandSeq({ @@ -9448,8 +9664,7 @@ export function Test2() { content: "{}", }; - const host = createServerHost([aTs, bTs, tsconfig]); - const session = createSession(host); + const session = createSession(createServerHost([aTs, bTs, tsconfig])); openFilesForSession([aTs, bTs], session); const requestLocation: protocol.FileLocationRequestArgs = { @@ -9501,7 +9716,7 @@ export function Test2() { kindModifiers: ScriptElementKindModifier.exportedModifier, name: "foo", source: [{ text: "./a", kind: "text" }], - tags: emptyArray, + tags: undefined, }; assert.deepEqual | undefined>(detailsResponse, [ { @@ -9555,6 +9770,58 @@ export function Test2() { }); }); + describe("tsserverProjectSystem rename", () => { + it("works with fileToRename", () => { + const aTs: File = { path: "/a.ts", content: "export const a = 0;" }; + const bTs: File = { path: "/b.ts", content: 'import { a } from "./a";' }; + + const session = createSession(createServerHost([aTs, bTs])); + openFilesForSession([bTs], session); + + const response = executeSessionRequest(session, protocol.CommandTypes.Rename, protocolFileLocationFromSubstring(bTs, 'a";')); + assert.deepEqual(response, { + info: { + canRename: true, + fileToRename: aTs.path, + displayName: aTs.path, + fullDisplayName: aTs.path, + kind: ScriptElementKind.moduleElement, + kindModifiers: "", + triggerSpan: protocolTextSpanFromSubstring(bTs.content, "a", { index: 1 }), + }, + locs: [{ file: bTs.path, locs: [protocolRenameSpanFromSubstring(bTs.content, "./a")] }], + }); + }); + + it("works with prefixText and suffixText", () => { + const aTs: File = { path: "/a.ts", content: "const x = 0; const o = { x };" }; + const session = createSession(createServerHost([aTs])); + openFilesForSession([aTs], session); + + const response = executeSessionRequest(session, protocol.CommandTypes.Rename, protocolFileLocationFromSubstring(aTs, "x")); + assert.deepEqual(response, { + info: { + canRename: true, + fileToRename: undefined, + displayName: "x", + fullDisplayName: "x", + kind: ScriptElementKind.constElement, + kindModifiers: ScriptElementKindModifier.none, + triggerSpan: protocolTextSpanFromSubstring(aTs.content, "x"), + }, + locs: [ + { + file: aTs.path, + locs: [ + protocolRenameSpanFromSubstring(aTs.content, "x"), + protocolRenameSpanFromSubstring(aTs.content, "x", { index: 1 }, { prefixText: "x: " }), + ], + }, + ], + }); + }); + }); + describe("tsserverProjectSystem typeReferenceDirectives", () => { it("when typeReferenceDirective contains UpperCasePackage", () => { const projectLocation = "/user/username/projects/myproject"; @@ -9583,7 +9850,7 @@ declare class TestLib { constructor() { var l = new TestLib(); - + } public test2() { @@ -9612,6 +9879,32 @@ declare class TestLib { host.writeFile(appLib.path, appLib.content.replace("test()", "test2()")); host.checkTimeoutQueueLengthAndRun(2); }); + + it("when typeReferenceDirective is relative path and in a sibling folder", () => { + const projectRootPath = "/user/username/projects/browser-addon"; + const projectPath = `${projectRootPath}/background`; + const file: File = { + path: `${projectPath}/a.ts`, + content: "let x = 10;" + }; + const tsconfig: File = { + path: `${projectPath}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + types: [ + "../typedefs/filesystem" + ] } + }) + }; + const filesystem: File = { + path: `${projectRootPath}/typedefs/filesystem.d.ts`, + content: `interface LocalFileSystem { someProperty: string; }` + }; + const files = [file, tsconfig, filesystem, libFile]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(file.path); + }); }); describe("tsserverProjectSystem project references", () => { @@ -9739,7 +10032,7 @@ declare class TestLib { function verifyATsConfigOriginalProject(session: TestSession) { checkNumberOfProjects(session.getProjectService(), { inferredProjects: 1, configuredProjects: 1 }); verifyInferredProjectUnchanged(session); - verifyATsConfigProject(session); + verifyATsConfigProject(session); // Close user file should close all the projects closeFilesForSession([userTs], session); verifyOnlyOrphanInferredProject(session); @@ -9889,11 +10182,12 @@ declare class TestLib { verifyATsConfigWhenOpened(session); }); + interface ReferencesFullRequest extends protocol.FileLocationRequest { readonly command: protocol.CommandTypes.ReferencesFull; } + interface ReferencesFullResponse extends protocol.Response { readonly body: ReadonlyArray; } + it("findAllReferencesFull", () => { const session = makeSampleProjects(); - interface ReferencesFullRequest extends protocol.FileLocationRequest { command: protocol.CommandTypes.ReferencesFull; } - interface ReferencesFullResponse extends protocol.Response { body: ReadonlyArray; } const responseFull = executeSessionRequest(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(userTs, "fnA()")); function fnAVoid(kind: SymbolDisplayPartKind): SymbolDisplayPart[] { @@ -9950,6 +10244,67 @@ declare class TestLib { verifyATsConfigOriginalProject(session); }); + it("findAllReferencesFull definition is in mapped file", () => { + const aTs: File = { path: "/a/a.ts", content: `function f() {}` }; + const aTsconfig: File = { + path: "/a/tsconfig.json", + content: JSON.stringify({ compilerOptions: { declaration: true, declarationMap: true, outFile: "../bin/a.js" } }), + }; + const bTs: File = { path: "/b/b.ts", content: `f();` }; + const bTsconfig: File = { path: "/b/tsconfig.json", content: JSON.stringify({ references: [{ path: "../a" }] }) }; + const aDts: File = { path: "/bin/a.d.ts", content: `declare function f(): void;\n//# sourceMappingURL=a.d.ts.map` }; + const aDtsMap: File = { + path: "/bin/a.d.ts.map", + content: JSON.stringify({ version: 3, file: "a.d.ts", sourceRoot: "", sources: ["../a/a.ts"], names: [], mappings: "AAAA,iBAAS,CAAC,SAAK" }), + }; + + const session = createSession(createServerHost([aTs, aTsconfig, bTs, bTsconfig, aDts, aDtsMap])); + checkDeclarationFiles(aTs, session, [aDtsMap, aDts]); + openFilesForSession([bTs], session); + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 1 }); + + const responseFull = executeSessionRequest(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(bTs, "f()")); + + assert.deepEqual>(responseFull, [ + { + definition: { + containerKind: ScriptElementKind.unknown, + containerName: "", + displayParts: [ + keywordPart(SyntaxKind.FunctionKeyword), + spacePart(), + displayPart("f", SymbolDisplayPartKind.functionName), + punctuationPart(SyntaxKind.OpenParenToken), + punctuationPart(SyntaxKind.CloseParenToken), + punctuationPart(SyntaxKind.ColonToken), + spacePart(), + keywordPart(SyntaxKind.VoidKeyword), + ], + fileName: aTs.path, + kind: ScriptElementKind.functionElement, + name: "function f(): void", + textSpan: { start: 9, length: 1 }, + }, + references: [ + { + fileName: bTs.path, + isDefinition: false, + isInString: undefined, + isWriteAccess: false, + textSpan: { start: 0, length: 1 }, + }, + { + fileName: aTs.path, + isDefinition: true, + isInString: undefined, + isWriteAccess: true, + textSpan: { start: 9, length: 1 }, + }, + ], + } + ]); + }); + it("findAllReferences -- target does not exist", () => { const session = makeSampleProjects(); @@ -9969,13 +10324,13 @@ declare class TestLib { const renameATs = (aTs: File): protocol.SpanGroup => ({ file: aTs.path, - locs: [protocolTextSpanFromSubstring(aTs.content, "fnA")], + locs: [protocolRenameSpanFromSubstring(aTs.content, "fnA")], }); const renameUserTs = (userTs: File): protocol.SpanGroup => ({ file: userTs.path, locs: [ - protocolTextSpanFromSubstring(userTs.content, "fnA"), - protocolTextSpanFromSubstring(userTs.content, "fnA", { index: 1 }), + protocolRenameSpanFromSubstring(userTs.content, "fnA"), + protocolRenameSpanFromSubstring(userTs.content, "fnA", { index: 1 }), ], }); @@ -9986,10 +10341,11 @@ declare class TestLib { info: { canRename: true, displayName: "fnA", + fileToRename: undefined, fullDisplayName: "fnA", kind: ScriptElementKind.alias, kindModifiers: ScriptElementKindModifier.none, - localizedErrorMessage: undefined, + triggerSpan: protocolTextSpanFromSubstring(userTs.content, "fnA", { index: 1 }), }, locs: [renameUserTs(userTs), renameATs(aTs)], }); @@ -10004,10 +10360,11 @@ declare class TestLib { info: { canRename: true, displayName: "fnA", + fileToRename: undefined, fullDisplayName: '"/a/a".fnA', kind: ScriptElementKind.functionElement, kindModifiers: ScriptElementKindModifier.exportedModifier, - localizedErrorMessage: undefined, + triggerSpan: protocolTextSpanFromSubstring(aTs.content, "fnA"), }, locs: [renameATs(aTs), renameUserTs(userTs)], }); @@ -10018,9 +10375,9 @@ declare class TestLib { const session = makeSampleProjects(); const response = executeSessionRequest(session, protocol.CommandTypes.RenameLocationsFull, protocolFileLocationFromSubstring(userTs, "fnA()")); assert.deepEqual>(response, [ - documentSpanFromSubstring(userTs, "fnA"), - documentSpanFromSubstring(userTs, "fnA", { index: 1 }), - documentSpanFromSubstring(aTs, "fnA"), + renameLocation(userTs, "fnA"), + renameLocation(userTs, "fnA", { index: 1 }), + renameLocation(aTs, "fnA"), ]); verifyATsConfigOriginalProject(session); }); @@ -10032,22 +10389,23 @@ declare class TestLib { info: { canRename: true, displayName: "fnB", + fileToRename: undefined, fullDisplayName: "fnB", kind: ScriptElementKind.alias, kindModifiers: ScriptElementKindModifier.none, - localizedErrorMessage: undefined, + triggerSpan: protocolTextSpanFromSubstring(userTs.content, "fnB", { index: 1 }), }, locs: [ { file: userTs.path, locs: [ - protocolTextSpanFromSubstring(userTs.content, "fnB"), - protocolTextSpanFromSubstring(userTs.content, "fnB", { index: 1 }), + protocolRenameSpanFromSubstring(userTs.content, "fnB"), + protocolRenameSpanFromSubstring(userTs.content, "fnB", { index: 1 }), ], }, { file: bDts.path, - locs: [protocolTextSpanFromSubstring(bDts.content, "fnB")], + locs: [protocolRenameSpanFromSubstring(bDts.content, "fnB")], } ], }); @@ -10169,6 +10527,35 @@ declare class TestLib { }); }); + describe("tsserverProjectSystem config file change", () => { + it("Updates diagnostics when '--noUnusedLabels' changes", () => { + const aTs: File = { path: "/a.ts", content: "label: while (1) {}" }; + const options = (allowUnusedLabels: boolean) => `{ "compilerOptions": { "allowUnusedLabels": ${allowUnusedLabels} } }`; + const tsconfig: File = { path: "/tsconfig.json", content: options(/*allowUnusedLabels*/ true) }; + + const host = createServerHost([aTs, tsconfig]); + const session = createSession(host); + openFilesForSession([aTs], session); + + host.modifyFile(tsconfig.path, options(/*allowUnusedLabels*/ false)); + host.runQueuedTimeoutCallbacks(); + + const response = executeSessionRequest(session, protocol.CommandTypes.SemanticDiagnosticsSync, { file: aTs.path }) as protocol.Diagnostic[] | undefined; + assert.deepEqual(response, [ + { + start: { line: 1, offset: 1 }, + end: { line: 1, offset: 1 + "label".length }, + text: "Unused label.", + category: "error", + code: Diagnostics.Unused_label.code, + relatedInformation: undefined, + reportsUnnecessary: true, + source: undefined, + }, + ]); + }); + }); + function makeReferenceItem(file: File, isDefinition: boolean, text: string, lineText: string, options?: SpanFromSubstringOptions): protocol.ReferencesResponseItem { return { ...protocolFileSpanFromSubstring(file, text, options), diff --git a/src/testRunner/unittests/typingsInstaller.ts b/src/testRunner/unittests/typingsInstaller.ts index 6a7e76e15de..a718a12f548 100644 --- a/src/testRunner/unittests/typingsInstaller.ts +++ b/src/testRunner/unittests/typingsInstaller.ts @@ -1322,7 +1322,7 @@ namespace ts.projectSystem { content: "" }; const host = createServerHost([f, node]); - const cache = createMapFromTemplate({ node: { typingLocation: node.path, version: Semver.parse("1.3.0") } }); + const cache = createMapFromTemplate({ node: { typingLocation: node.path, version: new Version("1.3.0") } }); const registry = createTypesRegistry("node"); const logger = trackingLogger(); const result = JsTyping.discoverTypings(host, logger.log, [f.path], getDirectoryPath(f.path), emptySafeList, cache, { enable: true }, ["fs", "bar"], registry); @@ -1344,7 +1344,7 @@ namespace ts.projectSystem { content: "" }; const host = createServerHost([f, node]); - const cache = createMapFromTemplate({ node: { typingLocation: node.path, version: Semver.parse("1.3.0") } }); + const cache = createMapFromTemplate({ node: { typingLocation: node.path, version: new Version("1.3.0") } }); const logger = trackingLogger(); const result = JsTyping.discoverTypings(host, logger.log, [f.path], getDirectoryPath(f.path), emptySafeList, cache, { enable: true }, ["fs", "bar"], emptyMap); assert.deepEqual(logger.finish(), [ @@ -1401,8 +1401,8 @@ namespace ts.projectSystem { }; const host = createServerHost([app]); const cache = createMapFromTemplate({ - node: { typingLocation: node.path, version: Semver.parse("1.3.0") }, - commander: { typingLocation: commander.path, version: Semver.parse("1.0.0") } + node: { typingLocation: node.path, version: new Version("1.3.0") }, + commander: { typingLocation: commander.path, version: new Version("1.0.0") } }); const registry = createTypesRegistry("node", "commander"); const logger = trackingLogger(); @@ -1427,7 +1427,7 @@ namespace ts.projectSystem { }; const host = createServerHost([app]); const cache = createMapFromTemplate({ - node: { typingLocation: node.path, version: Semver.parse("1.0.0") } + node: { typingLocation: node.path, version: new Version("1.0.0") } }); const registry = createTypesRegistry("node"); registry.delete(`ts${versionMajorMinor}`); @@ -1458,8 +1458,8 @@ namespace ts.projectSystem { }; const host = createServerHost([app]); const cache = createMapFromTemplate({ - node: { typingLocation: node.path, version: Semver.parse("1.3.0-next.0") }, - commander: { typingLocation: commander.path, version: Semver.parse("1.3.0-next.0") } + node: { typingLocation: node.path, version: new Version("1.3.0-next.0") }, + commander: { typingLocation: commander.path, version: new Version("1.3.0-next.0") } }); const registry = createTypesRegistry("node", "commander"); registry.get("node")![`ts${versionMajorMinor}`] = "1.3.0-next.1"; diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index d3966071265..ec2d029e60a 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -53,14 +53,10 @@ namespace ts { } export function executeCommandLine(args: string[]): void { - if (args.length > 0 && ((args[0].toLowerCase() === "--build") || (args[0].toLowerCase() === "-b"))) { - const result = performBuild(args.slice(1)); - // undefined = in watch mode, do not exit - if (result !== undefined) { - return sys.exit(result); - } - else { - return; + if (args.length > 0 && args[0].charCodeAt(0) === CharacterCodes.minus) { + const firstOption = args[0].slice(args[0].charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase(); + if (firstOption === "build" || firstOption === "b") { + return performBuild(args.slice(1)); } } @@ -164,40 +160,30 @@ namespace ts { } } - function performBuild(args: string[]): number | undefined { - const { buildOptions, projects: buildProjects, errors } = parseBuildCommand(args); + function performBuild(args: string[]) { + const { buildOptions, projects, errors } = parseBuildCommand(args); if (errors.length > 0) { errors.forEach(reportDiagnostic); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (buildOptions.help) { printVersion(); printHelp(buildOpts, "--build "); - return ExitStatus.Success; + return sys.exit(ExitStatus.Success); } // Update to pretty if host supports it updateReportDiagnostic(); - const projects = mapDefined(buildProjects, project => { - const fileName = resolvePath(sys.getCurrentDirectory(), project); - const refPath = resolveProjectReferencePath(sys, { path: fileName }); - if (!sys.fileExists(refPath)) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_0_does_not_exist, fileName)); - return undefined; - } - return refPath; - }); - if (projects.length === 0) { printVersion(); printHelp(buildOpts, "--build "); - return ExitStatus.Success; + return sys.exit(ExitStatus.Success); } if (!sys.getModifiedTime || !sys.setModifiedTime || (buildOptions.clean && !sys.deleteFile)) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (buildOptions.watch) { reportWatchModeWithoutSysSupport(); @@ -206,16 +192,15 @@ namespace ts { // TODO: change this to host if watch => watchHost otherwiue without wathc const builder = createSolutionBuilder(createSolutionBuilderWithWatchHost(sys, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty()), createWatchStatusReporter()), projects, buildOptions); if (buildOptions.clean) { - return builder.cleanAllProjects(); + return sys.exit(builder.cleanAllProjects()); } if (buildOptions.watch) { builder.buildAllProjects(); - builder.startWatching(); - return undefined; + return builder.startWatching(); } - return builder.buildAllProjects(); + return sys.exit(builder.buildAllProjects()); } function performCompilation(rootNames: string[], projectReferences: ReadonlyArray | undefined, options: CompilerOptions, configFileParsingDiagnostics?: ReadonlyArray) { @@ -237,12 +222,12 @@ namespace ts { function updateWatchCompilationHost(watchCompilerHost: WatchCompilerHost) { const compileUsingBuilder = watchCompilerHost.createProgram; - watchCompilerHost.createProgram = (rootNames, options, host, oldProgram, configFileParsingDiagnostics) => { + watchCompilerHost.createProgram = (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) => { Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); if (options !== undefined) { enableStatistics(options); } - return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics); + return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); }; const emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate!; // TODO: GH#18217 watchCompilerHost.afterProgramCreate = builderProgram => { diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 95b228f6e96..8a5c5b50906 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -231,7 +231,8 @@ namespace ts.server { // buffer, but we have yet to find a way to retrieve that value. private static readonly maxActiveRequestCount = 10; private static readonly requestDelayMillis = 100; - private packageInstalledPromise: { resolve(value: ApplyCodeActionCommandResult): void, reject(reason: any): void } | undefined; + private packageInstalledPromise: { resolve(value: ApplyCodeActionCommandResult): void, reject(reason: unknown): void } | undefined; + private inspectValuePromise: { resolve(value: ValueInfo): void } | undefined; constructor( private readonly telemetryEnabled: boolean, @@ -261,14 +262,19 @@ namespace ts.server { } installPackage(options: InstallPackageOptionsWithProject): Promise { - const rq: InstallPackageRequest = { kind: "installPackage", ...options }; - this.send(rq); + this.send({ kind: "installPackage", ...options }); Debug.assert(this.packageInstalledPromise === undefined); - return new Promise((resolve, reject) => { + return new Promise((resolve, reject) => { this.packageInstalledPromise = { resolve, reject }; }); } + inspectValue(options: InspectValueOptions): Promise { + this.send({ kind: "inspectValue", options }); + Debug.assert(this.inspectValuePromise === undefined); + return new Promise(resolve => { this.inspectValuePromise = { resolve }; }); + } + attach(projectService: ProjectService) { this.projectService = projectService; if (this.logger.hasLevel(LogLevel.requestTime)) { @@ -320,7 +326,7 @@ namespace ts.server { this.send({ projectName: p.getProjectName(), kind: "closeProject" }); } - private send(rq: TypingInstallerRequestUnion): void { + private send(rq: T): void { this.installer.send(rq); } @@ -353,7 +359,7 @@ namespace ts.server { } } - private handleMessage(response: TypesRegistryResponse | PackageInstalledResponse | SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | InitializationFailedResponse) { + private handleMessage(response: TypesRegistryResponse | PackageInstalledResponse | InspectValueResponse | SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | InitializationFailedResponse) { if (this.logger.hasLevel(LogLevel.verbose)) { this.logger.info(`Received response:${stringifyIndented(response)}`); } @@ -378,6 +384,10 @@ namespace ts.server { this.event(response, "setTypings"); break; } + case ActionValueInspected: + this.inspectValuePromise!.resolve(response.result); + this.inspectValuePromise = undefined; + break; case EventInitializationFailed: { const body: protocol.TypesInstallerInitializationFailedEventBody = { @@ -510,6 +520,7 @@ namespace ts.server { globalPlugins, pluginProbeLocations, allowLocalPluginLoads, + typesMapLocation, }); this.eventPort = eventPort; @@ -891,7 +902,7 @@ namespace ts.server { sys.require = (initialDir: string, moduleName: string): RequireResult => { try { - return { module: require(resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; + return { module: require(resolveJSModule(moduleName, initialDir, sys)), error: undefined }; } catch (error) { return { module: undefined, error }; diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index d2c7269f9bf..62bdcfce260 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -1,5 +1,3 @@ -// tslint:disable no-unnecessary-type-assertion (TODO: tslint can't find node types) - namespace ts.server.typingsInstaller { const fs: { appendFileSync(file: string, content: string): void @@ -12,19 +10,20 @@ namespace ts.server.typingsInstaller { } = require("path"); class FileLog implements Log { - private logEnabled = true; - constructor(private readonly logFile?: string) { + constructor(private logFile: string | undefined) { } isEnabled = () => { - return this.logEnabled && this.logFile !== undefined; + return typeof this.logFile === "string"; } writeLine = (text: string) => { + if (typeof this.logFile !== "string") return; + try { - fs.appendFileSync(this.logFile!, `[${nowString()}] ${text}${sys.newLine}`); // TODO: GH#18217 + fs.appendFileSync(this.logFile, `[${nowString()}] ${text}${sys.newLine}`); } catch (e) { - this.logEnabled = false; + this.logFile = undefined; } } } @@ -164,6 +163,11 @@ namespace ts.server.typingsInstaller { } break; } + case "inspectValue": { + const response: InspectValueResponse = { kind: ActionValueInspected, result: inspectModule(req.options.fileNameToRequire) }; + this.sendResponse(response); + break; + } default: Debug.assertNever(req); } diff --git a/src/typingsInstallerCore/typingsInstaller.ts b/src/typingsInstallerCore/typingsInstaller.ts index 44a51a01779..df83f1a677c 100644 --- a/src/typingsInstallerCore/typingsInstaller.ts +++ b/src/typingsInstallerCore/typingsInstaller.ts @@ -252,8 +252,11 @@ namespace ts.server.typingsInstaller { } const info = getProperty(npmLock.dependencies, key); const version = info && info.version; - const semver = Semver.parse(version!); // TODO: GH#18217 - const newTyping: JsTyping.CachedTyping = { typingLocation: typingFile, version: semver }; + if (!version) { + continue; + } + + const newTyping: JsTyping.CachedTyping = { typingLocation: typingFile, version: new Version(version) }; this.packageNameToTypingLocation.set(packageName, newTyping); } } @@ -356,7 +359,7 @@ namespace ts.server.typingsInstaller { // packageName is guaranteed to exist in typesRegistry by filterTypings const distTags = this.typesRegistry.get(packageName)!; - const newVersion = Semver.parse(distTags[`ts${versionMajorMinor}`] || distTags[this.latestDistTag]); + const newVersion = new Version(distTags[`ts${versionMajorMinor}`] || distTags[this.latestDistTag]); const newTyping: JsTyping.CachedTyping = { typingLocation: typingFile, version: newVersion }; this.packageNameToTypingLocation.set(packageName, newTyping); installedTypingFiles.push(typingFile); diff --git a/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt b/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt index 232f476f66c..6622033a687 100644 --- a/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt +++ b/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(9,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(9,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(14,15): error TS2569: Type 'StringIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. @@ -13,7 +13,7 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(14,1 } [Symbol.iterator]() { ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. return this; } } diff --git a/tests/baselines/reference/ES5SymbolProperty2.errors.txt b/tests/baselines/reference/ES5SymbolProperty2.errors.txt index 0535da56f06..2115ed99979 100644 --- a/tests/baselines/reference/ES5SymbolProperty2.errors.txt +++ b/tests/baselines/reference/ES5SymbolProperty2.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(5,10): error TS2471: A computed property name of the form 'Symbol.iterator' must be of type 'symbol'. -tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(10,11): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(10,11): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/Symbols/ES5SymbolProperty2.ts (2 errors) ==== @@ -16,4 +16,4 @@ tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(10,11): error TS2693: 'Sym (new M.C)[Symbol.iterator]; ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. \ No newline at end of file +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. \ No newline at end of file diff --git a/tests/baselines/reference/ES5SymbolProperty6.errors.txt b/tests/baselines/reference/ES5SymbolProperty6.errors.txt index e359f9b73ba..4357fe6a62f 100644 --- a/tests/baselines/reference/ES5SymbolProperty6.errors.txt +++ b/tests/baselines/reference/ES5SymbolProperty6.errors.txt @@ -1,14 +1,14 @@ -tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. -tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(5,9): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(5,9): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/Symbols/ES5SymbolProperty6.ts (2 errors) ==== class C { [Symbol.iterator]() { } ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } (new C)[Symbol.iterator] ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. \ No newline at end of file +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. \ No newline at end of file diff --git a/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js b/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js index e609e3d1e6c..9074e2ad4c8 100644 --- a/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js +++ b/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js @@ -27,7 +27,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js b/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js index 29416ab80b3..7ffab769794 100644 --- a/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js +++ b/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js @@ -31,7 +31,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json index 73d3f598059..f75d1e5fc6b 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json @@ -30,7 +30,7 @@ { "kind": "JSDocParameterTag", "pos": 34, - "end": 54, + "end": 64, "atToken": { "kind": "AtToken", "pos": 34, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json index 6d2fb4ada2f..7b3050cffa2 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json @@ -38,7 +38,7 @@ { "kind": "JSDocPropertyTag", "pos": 47, - "end": 72, + "end": 74, "atToken": { "kind": "AtToken", "pos": 47, @@ -72,7 +72,7 @@ { "kind": "JSDocPropertyTag", "pos": 74, - "end": 97, + "end": 100, "atToken": { "kind": "AtToken", "pos": 74, diff --git a/tests/baselines/reference/abstractClassInLocalScope.js b/tests/baselines/reference/abstractClassInLocalScope.js index afcefadb705..4e7b9f87095 100644 --- a/tests/baselines/reference/abstractClassInLocalScope.js +++ b/tests/baselines/reference/abstractClassInLocalScope.js @@ -14,7 +14,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/abstractClassInLocalScopeIsAbstract.js b/tests/baselines/reference/abstractClassInLocalScopeIsAbstract.js index ec27e0d91fd..60af14e625b 100644 --- a/tests/baselines/reference/abstractClassInLocalScopeIsAbstract.js +++ b/tests/baselines/reference/abstractClassInLocalScopeIsAbstract.js @@ -14,7 +14,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/abstractProperty.js b/tests/baselines/reference/abstractProperty.js index ca9bf0c3742..a7d63d55452 100644 --- a/tests/baselines/reference/abstractProperty.js +++ b/tests/baselines/reference/abstractProperty.js @@ -28,7 +28,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/abstractPropertyInConstructor.errors.txt b/tests/baselines/reference/abstractPropertyInConstructor.errors.txt index 5337bfc538a..869ec3b1e65 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.errors.txt +++ b/tests/baselines/reference/abstractPropertyInConstructor.errors.txt @@ -2,9 +2,10 @@ tests/cases/compiler/abstractPropertyInConstructor.ts(4,24): error TS2715: Abstr tests/cases/compiler/abstractPropertyInConstructor.ts(7,18): error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. tests/cases/compiler/abstractPropertyInConstructor.ts(9,14): error TS2715: Abstract property 'cb' in class 'AbstractClass' cannot be accessed in the constructor. tests/cases/compiler/abstractPropertyInConstructor.ts(25,18): error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. +tests/cases/compiler/abstractPropertyInConstructor.ts(39,22): error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. -==== tests/cases/compiler/abstractPropertyInConstructor.ts (4 errors) ==== +==== tests/cases/compiler/abstractPropertyInConstructor.ts (5 errors) ==== abstract class AbstractClass { constructor(str: string, other: AbstractClass) { this.method(parseInt(str)); @@ -45,6 +46,38 @@ tests/cases/compiler/abstractPropertyInConstructor.ts(25,18): error TS2715: Abst } } + abstract class DerivedAbstractClass extends AbstractClass { + cb = (s: string) => {}; + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { + super(str, other); + // there is no implementation of 'prop' in any base class + this.cb(this.prop.toLowerCase()); + ~~~~ +!!! error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. + + this.method(1); + + // OK, references are to another instance + other.cb(other.prop); + yetAnother.cb(yetAnother.prop); + } + } + + class Implementation extends DerivedAbstractClass { + prop = ""; + cb = (s: string) => {}; + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { + super(str, other, yetAnother); + this.cb(this.prop); + } + + method(n: number) { + this.cb(this.prop + n); + } + } + class User { constructor(a: AbstractClass) { a.prop; diff --git a/tests/baselines/reference/abstractPropertyInConstructor.js b/tests/baselines/reference/abstractPropertyInConstructor.js index 782419ac67b..ab830664d51 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.js +++ b/tests/baselines/reference/abstractPropertyInConstructor.js @@ -31,6 +31,36 @@ abstract class AbstractClass { } } +abstract class DerivedAbstractClass extends AbstractClass { + cb = (s: string) => {}; + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { + super(str, other); + // there is no implementation of 'prop' in any base class + this.cb(this.prop.toLowerCase()); + + this.method(1); + + // OK, references are to another instance + other.cb(other.prop); + yetAnother.cb(yetAnother.prop); + } +} + +class Implementation extends DerivedAbstractClass { + prop = ""; + cb = (s: string) => {}; + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { + super(str, other, yetAnother); + this.cb(this.prop); + } + + method(n: number) { + this.cb(this.prop + n); + } +} + class User { constructor(a: AbstractClass) { a.prop; @@ -42,6 +72,19 @@ class User { //// [abstractPropertyInConstructor.js] +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); var AbstractClass = /** @class */ (function () { function AbstractClass(str, other) { var _this = this; @@ -65,6 +108,35 @@ var AbstractClass = /** @class */ (function () { }; return AbstractClass; }()); +var DerivedAbstractClass = /** @class */ (function (_super) { + __extends(DerivedAbstractClass, _super); + function DerivedAbstractClass(str, other, yetAnother) { + var _this = _super.call(this, str, other) || this; + _this.cb = function (s) { }; + // there is no implementation of 'prop' in any base class + _this.cb(_this.prop.toLowerCase()); + _this.method(1); + // OK, references are to another instance + other.cb(other.prop); + yetAnother.cb(yetAnother.prop); + return _this; + } + return DerivedAbstractClass; +}(AbstractClass)); +var Implementation = /** @class */ (function (_super) { + __extends(Implementation, _super); + function Implementation(str, other, yetAnother) { + var _this = _super.call(this, str, other, yetAnother) || this; + _this.prop = ""; + _this.cb = function (s) { }; + _this.cb(_this.prop); + return _this; + } + Implementation.prototype.method = function (n) { + this.cb(this.prop + n); + }; + return Implementation; +}(DerivedAbstractClass)); var User = /** @class */ (function () { function User(a) { a.prop; diff --git a/tests/baselines/reference/abstractPropertyInConstructor.symbols b/tests/baselines/reference/abstractPropertyInConstructor.symbols index 71f897118c8..628ee5c8576 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.symbols +++ b/tests/baselines/reference/abstractPropertyInConstructor.symbols @@ -92,31 +92,134 @@ abstract class AbstractClass { } } +abstract class DerivedAbstractClass extends AbstractClass { +>DerivedAbstractClass : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>AbstractClass : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) + + cb = (s: string) => {}; +>cb : Symbol(DerivedAbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 32, 59)) +>s : Symbol(s, Decl(abstractPropertyInConstructor.ts, 33, 10)) + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { +>str : Symbol(str, Decl(abstractPropertyInConstructor.ts, 35, 16)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 35, 28)) +>AbstractClass : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) +>yetAnother : Symbol(yetAnother, Decl(abstractPropertyInConstructor.ts, 35, 50)) +>DerivedAbstractClass : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) + + super(str, other); +>super : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) +>str : Symbol(str, Decl(abstractPropertyInConstructor.ts, 35, 16)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 35, 28)) + + // there is no implementation of 'prop' in any base class + this.cb(this.prop.toLowerCase()); +>this.cb : Symbol(DerivedAbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 32, 59)) +>this : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>cb : Symbol(DerivedAbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 32, 59)) +>this.prop.toLowerCase : Symbol(String.toLowerCase, Decl(lib.es5.d.ts, --, --)) +>this.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) +>this : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) +>toLowerCase : Symbol(String.toLowerCase, Decl(lib.es5.d.ts, --, --)) + + this.method(1); +>this.method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) +>this : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) + + // OK, references are to another instance + other.cb(other.prop); +>other.cb : Symbol(AbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 19, 26)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 35, 28)) +>cb : Symbol(AbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 19, 26)) +>other.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 35, 28)) +>prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) + + yetAnother.cb(yetAnother.prop); +>yetAnother.cb : Symbol(DerivedAbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 32, 59)) +>yetAnother : Symbol(yetAnother, Decl(abstractPropertyInConstructor.ts, 35, 50)) +>cb : Symbol(DerivedAbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 32, 59)) +>yetAnother.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) +>yetAnother : Symbol(yetAnother, Decl(abstractPropertyInConstructor.ts, 35, 50)) +>prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) + } +} + +class Implementation extends DerivedAbstractClass { +>Implementation : Symbol(Implementation, Decl(abstractPropertyInConstructor.ts, 46, 1)) +>DerivedAbstractClass : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) + + prop = ""; +>prop : Symbol(Implementation.prop, Decl(abstractPropertyInConstructor.ts, 48, 51)) + + cb = (s: string) => {}; +>cb : Symbol(Implementation.cb, Decl(abstractPropertyInConstructor.ts, 49, 14)) +>s : Symbol(s, Decl(abstractPropertyInConstructor.ts, 50, 10)) + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { +>str : Symbol(str, Decl(abstractPropertyInConstructor.ts, 52, 16)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 52, 28)) +>AbstractClass : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) +>yetAnother : Symbol(yetAnother, Decl(abstractPropertyInConstructor.ts, 52, 50)) +>DerivedAbstractClass : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) + + super(str, other, yetAnother); +>super : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>str : Symbol(str, Decl(abstractPropertyInConstructor.ts, 52, 16)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 52, 28)) +>yetAnother : Symbol(yetAnother, Decl(abstractPropertyInConstructor.ts, 52, 50)) + + this.cb(this.prop); +>this.cb : Symbol(Implementation.cb, Decl(abstractPropertyInConstructor.ts, 49, 14)) +>this : Symbol(Implementation, Decl(abstractPropertyInConstructor.ts, 46, 1)) +>cb : Symbol(Implementation.cb, Decl(abstractPropertyInConstructor.ts, 49, 14)) +>this.prop : Symbol(Implementation.prop, Decl(abstractPropertyInConstructor.ts, 48, 51)) +>this : Symbol(Implementation, Decl(abstractPropertyInConstructor.ts, 46, 1)) +>prop : Symbol(Implementation.prop, Decl(abstractPropertyInConstructor.ts, 48, 51)) + } + + method(n: number) { +>method : Symbol(Implementation.method, Decl(abstractPropertyInConstructor.ts, 55, 5)) +>n : Symbol(n, Decl(abstractPropertyInConstructor.ts, 57, 11)) + + this.cb(this.prop + n); +>this.cb : Symbol(Implementation.cb, Decl(abstractPropertyInConstructor.ts, 49, 14)) +>this : Symbol(Implementation, Decl(abstractPropertyInConstructor.ts, 46, 1)) +>cb : Symbol(Implementation.cb, Decl(abstractPropertyInConstructor.ts, 49, 14)) +>this.prop : Symbol(Implementation.prop, Decl(abstractPropertyInConstructor.ts, 48, 51)) +>this : Symbol(Implementation, Decl(abstractPropertyInConstructor.ts, 46, 1)) +>prop : Symbol(Implementation.prop, Decl(abstractPropertyInConstructor.ts, 48, 51)) +>n : Symbol(n, Decl(abstractPropertyInConstructor.ts, 57, 11)) + } +} + class User { ->User : Symbol(User, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>User : Symbol(User, Decl(abstractPropertyInConstructor.ts, 60, 1)) constructor(a: AbstractClass) { ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 63, 16)) >AbstractClass : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) a.prop; >a.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 63, 16)) >prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) a.cb("hi"); >a.cb : Symbol(AbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 19, 26)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 63, 16)) >cb : Symbol(AbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 19, 26)) a.method(12); >a.method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 63, 16)) >method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) a.method2(); >a.method2 : Symbol(AbstractClass.method2, Decl(abstractPropertyInConstructor.ts, 25, 25)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 63, 16)) >method2 : Symbol(AbstractClass.method2, Decl(abstractPropertyInConstructor.ts, 25, 25)) } } diff --git a/tests/baselines/reference/abstractPropertyInConstructor.types b/tests/baselines/reference/abstractPropertyInConstructor.types index 465e0fb2f04..8c8bd40aff0 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.types +++ b/tests/baselines/reference/abstractPropertyInConstructor.types @@ -104,6 +104,119 @@ abstract class AbstractClass { } } +abstract class DerivedAbstractClass extends AbstractClass { +>DerivedAbstractClass : DerivedAbstractClass +>AbstractClass : AbstractClass + + cb = (s: string) => {}; +>cb : (s: string) => void +>(s: string) => {} : (s: string) => void +>s : string + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { +>str : string +>other : AbstractClass +>yetAnother : DerivedAbstractClass + + super(str, other); +>super(str, other) : void +>super : typeof AbstractClass +>str : string +>other : AbstractClass + + // there is no implementation of 'prop' in any base class + this.cb(this.prop.toLowerCase()); +>this.cb(this.prop.toLowerCase()) : void +>this.cb : (s: string) => void +>this : this +>cb : (s: string) => void +>this.prop.toLowerCase() : string +>this.prop.toLowerCase : () => string +>this.prop : string +>this : this +>prop : string +>toLowerCase : () => string + + this.method(1); +>this.method(1) : void +>this.method : (num: number) => void +>this : this +>method : (num: number) => void +>1 : 1 + + // OK, references are to another instance + other.cb(other.prop); +>other.cb(other.prop) : void +>other.cb : (s: string) => void +>other : AbstractClass +>cb : (s: string) => void +>other.prop : string +>other : AbstractClass +>prop : string + + yetAnother.cb(yetAnother.prop); +>yetAnother.cb(yetAnother.prop) : void +>yetAnother.cb : (s: string) => void +>yetAnother : DerivedAbstractClass +>cb : (s: string) => void +>yetAnother.prop : string +>yetAnother : DerivedAbstractClass +>prop : string + } +} + +class Implementation extends DerivedAbstractClass { +>Implementation : Implementation +>DerivedAbstractClass : DerivedAbstractClass + + prop = ""; +>prop : string +>"" : "" + + cb = (s: string) => {}; +>cb : (s: string) => void +>(s: string) => {} : (s: string) => void +>s : string + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { +>str : string +>other : AbstractClass +>yetAnother : DerivedAbstractClass + + super(str, other, yetAnother); +>super(str, other, yetAnother) : void +>super : typeof DerivedAbstractClass +>str : string +>other : AbstractClass +>yetAnother : DerivedAbstractClass + + this.cb(this.prop); +>this.cb(this.prop) : void +>this.cb : (s: string) => void +>this : this +>cb : (s: string) => void +>this.prop : string +>this : this +>prop : string + } + + method(n: number) { +>method : (n: number) => void +>n : number + + this.cb(this.prop + n); +>this.cb(this.prop + n) : void +>this.cb : (s: string) => void +>this : this +>cb : (s: string) => void +>this.prop + n : string +>this.prop : string +>this : this +>prop : string +>n : number + } +} + class User { >User : User diff --git a/tests/baselines/reference/abstractPropertyNegative.js b/tests/baselines/reference/abstractPropertyNegative.js index 4db1f89ff0d..df07c9f7a3e 100644 --- a/tests/baselines/reference/abstractPropertyNegative.js +++ b/tests/baselines/reference/abstractPropertyNegative.js @@ -50,7 +50,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/accessOverriddenBaseClassMember1.js b/tests/baselines/reference/accessOverriddenBaseClassMember1.js index 3f290cc5369..6512ba01d67 100644 --- a/tests/baselines/reference/accessOverriddenBaseClassMember1.js +++ b/tests/baselines/reference/accessOverriddenBaseClassMember1.js @@ -22,7 +22,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/accessors_spec_section-4.5_inference.js b/tests/baselines/reference/accessors_spec_section-4.5_inference.js index 5ba098f7c2d..9be63d5e41a 100644 --- a/tests/baselines/reference/accessors_spec_section-4.5_inference.js +++ b/tests/baselines/reference/accessors_spec_section-4.5_inference.js @@ -31,7 +31,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols b/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols index 21ae7940f96..912798f4a1b 100644 --- a/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols +++ b/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols @@ -6,7 +6,7 @@ declare namespace demoNS { >f : Symbol(f, Decl(demo.d.ts, 0, 26)) } declare module 'demoModule' { ->'demoModule' : Symbol('demoModule', Decl(demo.d.ts, 2, 1)) +>'demoModule' : Symbol("demoModule", Decl(demo.d.ts, 2, 1)) import alias = demoNS; >alias : Symbol(alias, Decl(demo.d.ts, 3, 29)) diff --git a/tests/baselines/reference/aliasUsageInAccessorsOfClass.js b/tests/baselines/reference/aliasUsageInAccessorsOfClass.js index 34d2bf2ff49..107466601d3 100644 --- a/tests/baselines/reference/aliasUsageInAccessorsOfClass.js +++ b/tests/baselines/reference/aliasUsageInAccessorsOfClass.js @@ -44,7 +44,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/aliasUsageInArray.js b/tests/baselines/reference/aliasUsageInArray.js index 38535edd441..4282290a392 100644 --- a/tests/baselines/reference/aliasUsageInArray.js +++ b/tests/baselines/reference/aliasUsageInArray.js @@ -38,7 +38,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/aliasUsageInFunctionExpression.js b/tests/baselines/reference/aliasUsageInFunctionExpression.js index e573e530123..18ec4ed2c0a 100644 --- a/tests/baselines/reference/aliasUsageInFunctionExpression.js +++ b/tests/baselines/reference/aliasUsageInFunctionExpression.js @@ -37,7 +37,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/aliasUsageInGenericFunction.js b/tests/baselines/reference/aliasUsageInGenericFunction.js index db3a85835c5..9ec03624f1a 100644 --- a/tests/baselines/reference/aliasUsageInGenericFunction.js +++ b/tests/baselines/reference/aliasUsageInGenericFunction.js @@ -41,7 +41,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/aliasUsageInIndexerOfClass.js b/tests/baselines/reference/aliasUsageInIndexerOfClass.js index 282db192221..beb62454069 100644 --- a/tests/baselines/reference/aliasUsageInIndexerOfClass.js +++ b/tests/baselines/reference/aliasUsageInIndexerOfClass.js @@ -43,7 +43,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/aliasUsageInObjectLiteral.js b/tests/baselines/reference/aliasUsageInObjectLiteral.js index 1c794441f5c..aa70bdd700a 100644 --- a/tests/baselines/reference/aliasUsageInObjectLiteral.js +++ b/tests/baselines/reference/aliasUsageInObjectLiteral.js @@ -38,7 +38,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/aliasUsageInOrExpression.js b/tests/baselines/reference/aliasUsageInOrExpression.js index 75bc90302c5..e0969ae9901 100644 --- a/tests/baselines/reference/aliasUsageInOrExpression.js +++ b/tests/baselines/reference/aliasUsageInOrExpression.js @@ -41,7 +41,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js b/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js index 1faf2b813f3..8b6485aa2c4 100644 --- a/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js +++ b/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js @@ -41,7 +41,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -66,7 +66,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/aliasUsageInVarAssignment.js b/tests/baselines/reference/aliasUsageInVarAssignment.js index bf7871a27ac..e51718537f4 100644 --- a/tests/baselines/reference/aliasUsageInVarAssignment.js +++ b/tests/baselines/reference/aliasUsageInVarAssignment.js @@ -37,7 +37,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt b/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt index acb584f8fd9..ea5a7ddf30e 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt +++ b/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/a.ts(1,10): error TS2305: Module '"tests/cases/compiler/b"' has no exported member 'default'. +tests/cases/compiler/a.ts(1,10): error TS2305: Module '"./b"' has no exported member 'default'. ==== tests/cases/compiler/b.d.ts (0 errors) ==== @@ -9,6 +9,6 @@ tests/cases/compiler/a.ts(1,10): error TS2305: Module '"tests/cases/compiler/b"' ==== tests/cases/compiler/a.ts (1 errors) ==== import { default as Foo } from "./b"; ~~~~~~~ -!!! error TS2305: Module '"tests/cases/compiler/b"' has no exported member 'default'. +!!! error TS2305: Module '"./b"' has no exported member 'default'. Foo.bar(); Foo.foo(); \ No newline at end of file diff --git a/tests/baselines/reference/ambientConstLiterals.js b/tests/baselines/reference/ambientConstLiterals.js index b0b222128ac..c5c0fbaafbc 100644 --- a/tests/baselines/reference/ambientConstLiterals.js +++ b/tests/baselines/reference/ambientConstLiterals.js @@ -63,7 +63,7 @@ declare const c3 = "abc"; declare const c4 = 123; declare const c5 = 123; declare const c6 = -123; -declare const c7: boolean; +declare const c7 = true; declare const c8 = E.A; declare const c8b = E["non identifier"]; declare const c9: { diff --git a/tests/baselines/reference/ambientDeclarations.symbols b/tests/baselines/reference/ambientDeclarations.symbols index 1436c698cff..b4a6c394a91 100644 --- a/tests/baselines/reference/ambientDeclarations.symbols +++ b/tests/baselines/reference/ambientDeclarations.symbols @@ -160,7 +160,7 @@ var q = M1.fn(); // Ambient external module in the global module // Ambient external module with a string literal name that is a top level external module name declare module 'external1' { ->'external1' : Symbol('external1', Decl(ambientDeclarations.ts, 67, 16)) +>'external1' : Symbol("external1", Decl(ambientDeclarations.ts, 67, 16)) var q; >q : Symbol(q, Decl(ambientDeclarations.ts, 72, 7)) diff --git a/tests/baselines/reference/ambientDeclarationsExternal.symbols b/tests/baselines/reference/ambientDeclarationsExternal.symbols index 49f0775e136..f0d2ec28221 100644 --- a/tests/baselines/reference/ambientDeclarationsExternal.symbols +++ b/tests/baselines/reference/ambientDeclarationsExternal.symbols @@ -20,7 +20,7 @@ var n: number; === tests/cases/conformance/ambient/decls.ts === // Ambient external module with export assignment declare module 'equ' { ->'equ' : Symbol('equ', Decl(decls.ts, 0, 0)) +>'equ' : Symbol("equ", Decl(decls.ts, 0, 0)) var x; >x : Symbol(x, Decl(decls.ts, 2, 7)) @@ -30,7 +30,7 @@ declare module 'equ' { } declare module 'equ2' { ->'equ2' : Symbol('equ2', Decl(decls.ts, 4, 1)) +>'equ2' : Symbol("equ2", Decl(decls.ts, 4, 1)) var x: number; >x : Symbol(x, Decl(decls.ts, 7, 7)) diff --git a/tests/baselines/reference/ambientErrors.symbols b/tests/baselines/reference/ambientErrors.symbols index 90efbe8383a..308cce2b734 100644 --- a/tests/baselines/reference/ambientErrors.symbols +++ b/tests/baselines/reference/ambientErrors.symbols @@ -90,16 +90,16 @@ module M2 { >M2 : Symbol(M2, Decl(ambientErrors.ts, 42, 1)) declare module 'nope' { } ->'nope' : Symbol('nope', Decl(ambientErrors.ts, 45, 11)) +>'nope' : Symbol("nope", Decl(ambientErrors.ts, 45, 11)) } // Ambient external module with a string literal name that isn't a top level external module name declare module '../foo' { } ->'../foo' : Symbol('../foo', Decl(ambientErrors.ts, 47, 1)) +>'../foo' : Symbol("../foo", Decl(ambientErrors.ts, 47, 1)) // Ambient external module with export assignment and other exported members declare module 'bar' { ->'bar' : Symbol('bar', Decl(ambientErrors.ts, 50, 27)) +>'bar' : Symbol("bar", Decl(ambientErrors.ts, 50, 27)) var n; >n : Symbol(n, Decl(ambientErrors.ts, 54, 7)) diff --git a/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols b/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols index 621c7b3ebfc..75fb494da11 100644 --- a/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols +++ b/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols @@ -9,7 +9,7 @@ var c = new A(); === tests/cases/compiler/ambientExternalModuleWithInternalImportDeclaration_0.ts === declare module 'M' { ->'M' : Symbol('M', Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 0, 0)) +>'M' : Symbol("M", Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 0, 0)) module C { >C : Symbol(C, Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 0, 20), Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 3, 5)) diff --git a/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols b/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols index 6827122959d..625e5392893 100644 --- a/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols +++ b/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols @@ -9,7 +9,7 @@ var c = new A(); === tests/cases/compiler/ambientExternalModuleWithoutInternalImportDeclaration_0.ts === declare module 'M' { ->'M' : Symbol('M', Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 0, 0)) +>'M' : Symbol("M", Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 0, 0)) module C { >C : Symbol(C, Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 0, 20), Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 3, 5)) diff --git a/tests/baselines/reference/ambiguousOverloadResolution.js b/tests/baselines/reference/ambiguousOverloadResolution.js index 6e00d7b2374..56bef268fb4 100644 --- a/tests/baselines/reference/ambiguousOverloadResolution.js +++ b/tests/baselines/reference/ambiguousOverloadResolution.js @@ -15,7 +15,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js b/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js index 9d95712af40..a4b9d732c0b 100644 --- a/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js +++ b/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js @@ -28,7 +28,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js b/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js index 2b535bf45fd..9579d7c5a4a 100644 --- a/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js +++ b/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js @@ -15,7 +15,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/anonymousModules.errors.txt b/tests/baselines/reference/anonymousModules.errors.txt index 4893a0c80aa..b81513cfbbd 100644 --- a/tests/baselines/reference/anonymousModules.errors.txt +++ b/tests/baselines/reference/anonymousModules.errors.txt @@ -1,22 +1,22 @@ -tests/cases/compiler/anonymousModules.ts(1,1): error TS2304: Cannot find name 'module'. +tests/cases/compiler/anonymousModules.ts(1,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/anonymousModules.ts(1,8): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(4,2): error TS2304: Cannot find name 'module'. +tests/cases/compiler/anonymousModules.ts(4,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/anonymousModules.ts(4,9): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(10,2): error TS2304: Cannot find name 'module'. +tests/cases/compiler/anonymousModules.ts(10,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected. ==== tests/cases/compiler/anonymousModules.ts (6 errors) ==== module { ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. export var foo = 1; module { ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. export var bar = 1; @@ -26,7 +26,7 @@ tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected. module { ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. var x = bar; diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 2fa23f14a7b..a4cb439e623 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ const version: string; } @@ -69,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -1082,7 +1083,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1811,7 +1812,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -1939,7 +1941,6 @@ declare namespace ts { /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; @@ -2059,7 +2060,7 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, @@ -2493,6 +2494,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2584,7 +2586,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -4183,14 +4184,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4315,23 +4317,23 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; /** Host that has watch functionality used in --watch mode */ interface WatchHost { /** If provided, called with Diagnostic message that informs about change in watch status */ @@ -4393,6 +4395,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4427,8 +4431,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4442,6 +4446,7 @@ declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4450,7 +4455,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4658,6 +4663,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4715,9 +4721,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -4879,9 +4885,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -4947,6 +4960,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5099,15 +5114,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; @@ -6417,15 +6441,17 @@ declare namespace ts.server.protocol { /** * Information about the item to be renamed. */ - interface RenameInfo { + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { /** * True if item can be renamed. */ - canRename: boolean; + canRename: true; /** - * Error message if item can not be renamed. + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ - localizedErrorMessage?: string; + fileToRename?: string; /** * Display name of the item to be renamed. */ @@ -6442,6 +6468,15 @@ declare namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; } /** * A group of text spans, all in 'file'. @@ -6450,7 +6485,11 @@ declare namespace ts.server.protocol { /** The file to which the spans apply */ file: string; /** The text spans in this group */ - locs: TextSpan[]; + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface RenameResponseBody { /** @@ -7475,6 +7514,26 @@ declare namespace ts.server.protocol { */ openFiles: string[]; } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } type SurveyReadyEventName = "surveyReady"; interface SurveyReadyEvent extends Event { event: SurveyReadyEventName; @@ -8087,6 +8146,7 @@ declare namespace ts.server { useCaseSensitiveFileNames(): boolean; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile(fileName: string): string | undefined; + writeFile(fileName: string, content: string): void; fileExists(file: string): boolean; resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[]; getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; @@ -8226,6 +8286,8 @@ declare namespace ts.server { declare namespace ts.server { const maxProgramSizeForNonTsFiles: number; const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + const ProjectLoadingStartEvent = "projectLoadingStart"; + const ProjectLoadingFinishEvent = "projectLoadingFinish"; const SurveyReady = "surveyReady"; const LargeFileReferencedEvent = "largeFileReferenced"; const ConfigFileDiagEvent = "configFileDiag"; @@ -8238,6 +8300,19 @@ declare namespace ts.server { openFiles: string[]; }; } + interface ProjectLoadingStartEvent { + eventName: typeof ProjectLoadingStartEvent; + data: { + project: Project; + reason: string; + }; + } + interface ProjectLoadingFinishEvent { + eventName: typeof ProjectLoadingFinishEvent; + data: { + project: Project; + }; + } interface SurveyReady { eventName: typeof SurveyReady; data: { @@ -8322,7 +8397,7 @@ declare namespace ts.server { interface OpenFileInfo { readonly checkJs: boolean; } - type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; interface SafeList { [name: string]: { @@ -8372,6 +8447,7 @@ declare namespace ts.server { * Container of all known scripts */ private readonly filenameToScriptInfo; + private readonly scriptInfoInNodeModulesWatchers; /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -8420,7 +8496,7 @@ declare namespace ts.server { private readonly throttledOperations; private readonly hostConfiguration; private safelist; - private legacySafelist; + private readonly legacySafelist; private pendingProjectUpdates; readonly currentDirectory: NormalizedPath; readonly toCanonicalFileName: (f: string) => string; @@ -8542,6 +8618,10 @@ declare namespace ts.server { private createInferredProject; getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; private watchClosedScriptInfo; + private watchClosedScriptInfoInNodeModules; + private getModifiedTime; + private refreshScriptInfo; + private refreshScriptInfosInDirectory; private stopWatchingScriptInfo; private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; private getOrCreateScriptInfoOpenedByClientForNormalizedPath; @@ -8649,6 +8729,7 @@ declare namespace ts.server { globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; + typesMapLocation?: string; } class Session implements EventSender { private readonly gcTimer; @@ -8671,6 +8752,7 @@ declare namespace ts.server { private defaultEventHandler; private projectsUpdatedInBackgroundEvent; logError(err: Error, cmd: string): void; + private logErrorWorker; send(msg: protocol.Message): void; event(body: T, eventName: string): void; /** @deprecated */ @@ -8715,7 +8797,7 @@ declare namespace ts.server { private getProjects; private getDefaultProject; private getRenameLocations; - private static mapRenameInfo; + private mapRenameInfo; private toSpanGroups; private getReferences; /** diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 8290cb96236..89007faa746 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ const version: string; } @@ -69,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -1082,7 +1083,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1811,7 +1812,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -1939,7 +1941,6 @@ declare namespace ts { /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; @@ -2059,7 +2060,7 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, @@ -2493,6 +2494,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2584,7 +2586,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -4183,14 +4184,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4315,23 +4317,23 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; /** Host that has watch functionality used in --watch mode */ interface WatchHost { /** If provided, called with Diagnostic message that informs about change in watch status */ @@ -4393,6 +4395,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4427,8 +4431,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4442,6 +4446,7 @@ declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4450,7 +4455,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4658,6 +4663,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4715,9 +4721,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -4879,9 +4885,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -4947,6 +4960,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5099,15 +5114,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; diff --git a/tests/baselines/reference/apparentTypeSubtyping.js b/tests/baselines/reference/apparentTypeSubtyping.js index 6b153002813..2e9987f1e0d 100644 --- a/tests/baselines/reference/apparentTypeSubtyping.js +++ b/tests/baselines/reference/apparentTypeSubtyping.js @@ -30,7 +30,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/apparentTypeSupertype.js b/tests/baselines/reference/apparentTypeSupertype.js index 63e6345e5ba..82443d22197 100644 --- a/tests/baselines/reference/apparentTypeSupertype.js +++ b/tests/baselines/reference/apparentTypeSupertype.js @@ -20,7 +20,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt b/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt index 92764ddf90b..4ae19920e37 100644 --- a/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt +++ b/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/argumentsObjectIterator02_ES5.ts(2,26): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/compiler/argumentsObjectIterator02_ES5.ts(2,26): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/compiler/argumentsObjectIterator02_ES5.ts (1 errors) ==== function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { let blah = arguments[Symbol.iterator]; ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. let result = []; for (let arg of blah()) { diff --git a/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.errors.txt b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.errors.txt new file mode 100644 index 00000000000..788ff30c58f --- /dev/null +++ b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.errors.txt @@ -0,0 +1,19 @@ +tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts(5,1): error TS2554: Expected 3 arguments, but got 2. +tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts(7,1): error TS2554: Expected 3 arguments, but got 2. + + +==== tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts (2 errors) ==== + function foo(a, b, {c}): void {} + + function bar(a, b, [c]): void {} + + foo("", 0); + ~~~~~~~~~~ +!!! error TS2554: Expected 3 arguments, but got 2. +!!! related TS6211 tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts:1:20: An argument matching this binding pattern was not provided. + + bar("", 0); + ~~~~~~~~~~ +!!! error TS2554: Expected 3 arguments, but got 2. +!!! related TS6211 tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts:3:20: An argument matching this binding pattern was not provided. + \ No newline at end of file diff --git a/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.js b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.js new file mode 100644 index 00000000000..66f9316457d --- /dev/null +++ b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.js @@ -0,0 +1,19 @@ +//// [arityErrorRelatedSpanBindingPattern.ts] +function foo(a, b, {c}): void {} + +function bar(a, b, [c]): void {} + +foo("", 0); + +bar("", 0); + + +//// [arityErrorRelatedSpanBindingPattern.js] +function foo(a, b, _a) { + var c = _a.c; +} +function bar(a, b, _a) { + var c = _a[0]; +} +foo("", 0); +bar("", 0); diff --git a/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.symbols b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.symbols new file mode 100644 index 00000000000..f58194abaac --- /dev/null +++ b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts === +function foo(a, b, {c}): void {} +>foo : Symbol(foo, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 0)) +>a : Symbol(a, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 13)) +>b : Symbol(b, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 15)) +>c : Symbol(c, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 20)) + +function bar(a, b, [c]): void {} +>bar : Symbol(bar, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 32)) +>a : Symbol(a, Decl(arityErrorRelatedSpanBindingPattern.ts, 2, 13)) +>b : Symbol(b, Decl(arityErrorRelatedSpanBindingPattern.ts, 2, 15)) +>c : Symbol(c, Decl(arityErrorRelatedSpanBindingPattern.ts, 2, 20)) + +foo("", 0); +>foo : Symbol(foo, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 0)) + +bar("", 0); +>bar : Symbol(bar, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 32)) + diff --git a/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.types b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.types new file mode 100644 index 00000000000..954cb537665 --- /dev/null +++ b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts === +function foo(a, b, {c}): void {} +>foo : (a: any, b: any, { c }: { c: any; }) => void +>a : any +>b : any +>c : any + +function bar(a, b, [c]): void {} +>bar : (a: any, b: any, [c]: [any]) => void +>a : any +>b : any +>c : any + +foo("", 0); +>foo("", 0) : void +>foo : (a: any, b: any, { c }: { c: any; }) => void +>"" : "" +>0 : 0 + +bar("", 0); +>bar("", 0) : void +>bar : (a: any, b: any, [c]: [any]) => void +>"" : "" +>0 : 0 + diff --git a/tests/baselines/reference/arrayAssignmentTest1.js b/tests/baselines/reference/arrayAssignmentTest1.js index cf848855e5d..baf1e8bfa3a 100644 --- a/tests/baselines/reference/arrayAssignmentTest1.js +++ b/tests/baselines/reference/arrayAssignmentTest1.js @@ -92,7 +92,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/arrayAssignmentTest2.js b/tests/baselines/reference/arrayAssignmentTest2.js index 81176c8284f..5b1a655d781 100644 --- a/tests/baselines/reference/arrayAssignmentTest2.js +++ b/tests/baselines/reference/arrayAssignmentTest2.js @@ -66,7 +66,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/arrayBestCommonTypes.js b/tests/baselines/reference/arrayBestCommonTypes.js index c1251a50f38..7b8da4f7970 100644 --- a/tests/baselines/reference/arrayBestCommonTypes.js +++ b/tests/baselines/reference/arrayBestCommonTypes.js @@ -114,7 +114,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/arrayLiteralTypeInference.errors.txt b/tests/baselines/reference/arrayLiteralTypeInference.errors.txt index a2c4597127f..efffc256a83 100644 --- a/tests/baselines/reference/arrayLiteralTypeInference.errors.txt +++ b/tests/baselines/reference/arrayLiteralTypeInference.errors.txt @@ -1,14 +1,14 @@ -tests/cases/compiler/arrayLiteralTypeInference.ts(14,14): error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type 'Action[]'. - Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type 'Action'. - Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'. - Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'. -tests/cases/compiler/arrayLiteralTypeInference.ts(31,18): error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type '{ id: number; }[]'. - Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type '{ id: number; }'. - Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'. - Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'. +tests/cases/compiler/arrayLiteralTypeInference.ts(14,14): error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'. + Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'. +tests/cases/compiler/arrayLiteralTypeInference.ts(15,14): error TS2322: Type '{ id: number; name: string; }' is not assignable to type 'Action'. + Object literal may only specify known properties, and 'name' does not exist in type 'Action'. +tests/cases/compiler/arrayLiteralTypeInference.ts(31,18): error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'. + Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'. +tests/cases/compiler/arrayLiteralTypeInference.ts(32,18): error TS2322: Type '{ id: number; name: string; }' is not assignable to type '{ id: number; }'. + Object literal may only specify known properties, and 'name' does not exist in type '{ id: number; }'. -==== tests/cases/compiler/arrayLiteralTypeInference.ts (2 errors) ==== +==== tests/cases/compiler/arrayLiteralTypeInference.ts (4 errors) ==== class Action { id: number; } @@ -24,11 +24,12 @@ tests/cases/compiler/arrayLiteralTypeInference.ts(31,18): error TS2322: Type '({ var x1: Action[] = [ { id: 2, trueness: false }, ~~~~~~~~~~~~~~~ -!!! error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type 'Action[]'. -!!! error TS2322: Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type 'Action'. -!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'. -!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'. +!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'. +!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'. { id: 3, name: "three" } + ~~~~~~~~~~~~~ +!!! error TS2322: Type '{ id: number; name: string; }' is not assignable to type 'Action'. +!!! error TS2322: Object literal may only specify known properties, and 'name' does not exist in type 'Action'. ] var x2: Action[] = [ @@ -46,11 +47,12 @@ tests/cases/compiler/arrayLiteralTypeInference.ts(31,18): error TS2322: Type '({ [ { id: 2, trueness: false }, ~~~~~~~~~~~~~~~ -!!! error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type '{ id: number; }[]'. -!!! error TS2322: Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type '{ id: number; }'. -!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'. -!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'. +!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'. +!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'. { id: 3, name: "three" } + ~~~~~~~~~~~~~ +!!! error TS2322: Type '{ id: number; name: string; }' is not assignable to type '{ id: number; }'. +!!! error TS2322: Object literal may only specify known properties, and 'name' does not exist in type '{ id: number; }'. ] var z2: { id: number }[] = diff --git a/tests/baselines/reference/arrayLiteralTypeInference.js b/tests/baselines/reference/arrayLiteralTypeInference.js index 41cb85f8008..fcd8a62ce0b 100644 --- a/tests/baselines/reference/arrayLiteralTypeInference.js +++ b/tests/baselines/reference/arrayLiteralTypeInference.js @@ -58,7 +58,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/arrayLiterals.errors.txt b/tests/baselines/reference/arrayLiterals.errors.txt index f5fe71b79a6..4b9ca295f95 100644 --- a/tests/baselines/reference/arrayLiterals.errors.txt +++ b/tests/baselines/reference/arrayLiterals.errors.txt @@ -1,11 +1,10 @@ -tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts(24,77): error TS2322: Type '({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]' is not assignable to type '{ [n: number]: { a: string; b: number; }; }'. - Index signatures are incompatible. - Type '{ a: string; b: number; c: string; } | { a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'. - Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'. - Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts(24,77): error TS2322: Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'. + Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts(24,101): error TS2322: Type '{ a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'. + Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. -==== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts (1 errors) ==== +==== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts (2 errors) ==== // Empty array literal with no contextual type has type Undefined[] var arr1= [[], [1], ['']]; @@ -31,11 +30,13 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts(24,77): error // Contextual type C with numeric index signature makes array literal of EveryType E of type BCT(E,C)[] var context1: { [n: number]: { a: string; b: number; }; } = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }]; ~~~~~ -!!! error TS2322: Type '({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]' is not assignable to type '{ [n: number]: { a: string; b: number; }; }'. -!!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type '{ a: string; b: number; c: string; } | { a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'. -!!! error TS2322: Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'. -!!! error TS2322: Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. +!!! error TS2322: Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'. +!!! error TS2322: Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. +!!! related TS6501 tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts:24:17: The expected type comes from this index signature. + ~~~~ +!!! error TS2322: Type '{ a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'. +!!! error TS2322: Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. +!!! related TS6501 tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts:24:17: The expected type comes from this index signature. var context2 = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }]; // Contextual type C with numeric index signature of type Base makes array literal of Derived have type Base[] diff --git a/tests/baselines/reference/arrayLiterals.js b/tests/baselines/reference/arrayLiterals.js index bdc11c99e69..c4d257dd546 100644 --- a/tests/baselines/reference/arrayLiterals.js +++ b/tests/baselines/reference/arrayLiterals.js @@ -44,7 +44,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js b/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js index 49d1d33c2e8..25a76bec5c7 100644 --- a/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js +++ b/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js @@ -32,7 +32,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.js b/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.js index 47abb0d6255..45b587c0e62 100644 --- a/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.js +++ b/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.js @@ -26,7 +26,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/arraySigChecking.errors.txt b/tests/baselines/reference/arraySigChecking.errors.txt index 1968957363c..a1f219919d8 100644 --- a/tests/baselines/reference/arraySigChecking.errors.txt +++ b/tests/baselines/reference/arraySigChecking.errors.txt @@ -1,12 +1,10 @@ tests/cases/compiler/arraySigChecking.ts(11,17): error TS1023: An index signature parameter type must be 'string' or 'number'. -tests/cases/compiler/arraySigChecking.ts(18,5): error TS2322: Type 'void[]' is not assignable to type 'string[]'. - Type 'void' is not assignable to type 'string'. -tests/cases/compiler/arraySigChecking.ts(22,1): error TS2322: Type 'number[][]' is not assignable to type 'number[][][]'. - Type 'number[]' is not assignable to type 'number[][]'. - Type 'number' is not assignable to type 'number[]'. +tests/cases/compiler/arraySigChecking.ts(18,27): error TS2322: Type 'void' is not assignable to type 'string'. +tests/cases/compiler/arraySigChecking.ts(22,13): error TS2322: Type 'number' is not assignable to type 'number[]'. +tests/cases/compiler/arraySigChecking.ts(22,16): error TS2322: Type 'number' is not assignable to type 'number[]'. -==== tests/cases/compiler/arraySigChecking.ts (3 errors) ==== +==== tests/cases/compiler/arraySigChecking.ts (4 errors) ==== declare module M { interface iBar { t: any; } interface iFoo extends iBar { @@ -27,17 +25,16 @@ tests/cases/compiler/arraySigChecking.ts(22,1): error TS2322: Type 'number[][]' } var myVar: myInt; var strArray: string[] = [myVar.voidFn()]; - ~~~~~~~~ -!!! error TS2322: Type 'void[]' is not assignable to type 'string[]'. -!!! error TS2322: Type 'void' is not assignable to type 'string'. + ~~~~~~~~~~~~~~ +!!! error TS2322: Type 'void' is not assignable to type 'string'. var myArray: number[][][]; myArray = [[1, 2]]; - ~~~~~~~ -!!! error TS2322: Type 'number[][]' is not assignable to type 'number[][][]'. -!!! error TS2322: Type 'number[]' is not assignable to type 'number[][]'. -!!! error TS2322: Type 'number' is not assignable to type 'number[]'. + ~ +!!! error TS2322: Type 'number' is not assignable to type 'number[]'. + ~ +!!! error TS2322: Type 'number' is not assignable to type 'number[]'. function isEmpty(l: { length: number }) { return l.length === 0; diff --git a/tests/baselines/reference/arrowFunctionContexts.js b/tests/baselines/reference/arrowFunctionContexts.js index d32683f8ed8..466131ea206 100644 --- a/tests/baselines/reference/arrowFunctionContexts.js +++ b/tests/baselines/reference/arrowFunctionContexts.js @@ -102,7 +102,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatBug5.errors.txt b/tests/baselines/reference/assignmentCompatBug5.errors.txt index 44e28f15d8c..6a5c5569c8f 100644 --- a/tests/baselines/reference/assignmentCompatBug5.errors.txt +++ b/tests/baselines/reference/assignmentCompatBug5.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/assignmentCompatBug5.ts(2,8): error TS2345: Argument of type '{ b: number; }' is not assignable to parameter of type '{ a: number; }'. Object literal may only specify known properties, and 'b' does not exist in type '{ a: number; }'. -tests/cases/compiler/assignmentCompatBug5.ts(5,6): error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'number[]'. - Type 'string' is not assignable to type 'number'. +tests/cases/compiler/assignmentCompatBug5.ts(5,7): error TS2322: Type 'string' is not assignable to type 'number'. +tests/cases/compiler/assignmentCompatBug5.ts(5,12): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/compiler/assignmentCompatBug5.ts(8,6): error TS2345: Argument of type '(s: string) => void' is not assignable to parameter of type '(n: number) => number'. Types of parameters 's' and 'n' are incompatible. Type 'number' is not assignable to type 'string'. @@ -9,7 +9,7 @@ tests/cases/compiler/assignmentCompatBug5.ts(9,6): error TS2345: Argument of typ Type 'void' is not assignable to type 'number'. -==== tests/cases/compiler/assignmentCompatBug5.ts (4 errors) ==== +==== tests/cases/compiler/assignmentCompatBug5.ts (5 errors) ==== function foo1(x: { a: number; }) { } foo1({ b: 5 }); ~~~~ @@ -18,9 +18,10 @@ tests/cases/compiler/assignmentCompatBug5.ts(9,6): error TS2345: Argument of typ function foo2(x: number[]) { } foo2(["s", "t"]); - ~~~~~~~~~~ -!!! error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'number[]'. -!!! error TS2345: Type 'string' is not assignable to type 'number'. + ~~~ +!!! error TS2322: Type 'string' is not assignable to type 'number'. + ~~~ +!!! error TS2322: Type 'string' is not assignable to type 'number'. function foo3(x: (n: number) =>number) { }; foo3((s:string) => { }); diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures3.js b/tests/baselines/reference/assignmentCompatWithCallSignatures3.js index 2490b1ef9c8..a051b4e5194 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures3.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures3.js @@ -107,7 +107,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures4.js b/tests/baselines/reference/assignmentCompatWithCallSignatures4.js index d1e898d3c6d..fc83877023b 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures4.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures4.js @@ -106,7 +106,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures5.js b/tests/baselines/reference/assignmentCompatWithCallSignatures5.js index 6eaacacf897..fb6d0be1be1 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures5.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures5.js @@ -73,7 +73,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures6.js b/tests/baselines/reference/assignmentCompatWithCallSignatures6.js index 775d7886310..9e752a43a17 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures6.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures6.js @@ -50,7 +50,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js index 15ebdef5dad..932f9bb5d66 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js @@ -107,7 +107,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js index aa0ce793dce..4dad18cea8f 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js @@ -106,7 +106,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js index fbe0f53fa56..5f16895caf2 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js @@ -73,7 +73,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js index b476dd66420..dfce487fff1 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js @@ -50,7 +50,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithNumericIndexer.js b/tests/baselines/reference/assignmentCompatWithNumericIndexer.js index cbe47f21a95..6cdab6f3bed 100644 --- a/tests/baselines/reference/assignmentCompatWithNumericIndexer.js +++ b/tests/baselines/reference/assignmentCompatWithNumericIndexer.js @@ -51,7 +51,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js b/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js index cc8dc2fb1b8..54eb5e3ac9b 100644 --- a/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js +++ b/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js @@ -48,7 +48,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembers4.js b/tests/baselines/reference/assignmentCompatWithObjectMembers4.js index 46dfee1ed80..dd8d9d1bf46 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembers4.js +++ b/tests/baselines/reference/assignmentCompatWithObjectMembers4.js @@ -99,7 +99,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js index c53936f696e..fa8ca3f7ad8 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js +++ b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js @@ -96,7 +96,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js index 60793f2843f..918c2739ace 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js +++ b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js @@ -99,7 +99,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentCompatWithStringIndexer.js b/tests/baselines/reference/assignmentCompatWithStringIndexer.js index 62b22fc0091..9a67a00bac0 100644 --- a/tests/baselines/reference/assignmentCompatWithStringIndexer.js +++ b/tests/baselines/reference/assignmentCompatWithStringIndexer.js @@ -61,7 +61,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentLHSIsValue.js b/tests/baselines/reference/assignmentLHSIsValue.js index 1eacd789df1..dd7f28cb003 100644 --- a/tests/baselines/reference/assignmentLHSIsValue.js +++ b/tests/baselines/reference/assignmentLHSIsValue.js @@ -77,7 +77,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/assignmentToObjectAndFunction.errors.txt b/tests/baselines/reference/assignmentToObjectAndFunction.errors.txt index 8ba04d8ab2c..9e28f5e9177 100644 --- a/tests/baselines/reference/assignmentToObjectAndFunction.errors.txt +++ b/tests/baselines/reference/assignmentToObjectAndFunction.errors.txt @@ -10,7 +10,6 @@ tests/cases/compiler/assignmentToObjectAndFunction.ts(29,5): error TS2322: Type var errObj: Object = { toString: 0 }; // Error, incompatible toString ~~~~~~~~ !!! error TS2322: Type 'number' is not assignable to type '() => string'. -!!! related TS6500 /.ts/lib.es5.d.ts:125:5: The expected type comes from property 'toString' which is declared here on type 'Object' var goodObj: Object = { toString(x?) { return ""; diff --git a/tests/baselines/reference/asyncImportedPromise_es5.js b/tests/baselines/reference/asyncImportedPromise_es5.js index 5aabc56c56a..f17459321c8 100644 --- a/tests/baselines/reference/asyncImportedPromise_es5.js +++ b/tests/baselines/reference/asyncImportedPromise_es5.js @@ -17,7 +17,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js index 4b33d8492e9..2a910226703 100644 --- a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js +++ b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js @@ -2,14 +2,19 @@ class A { x() { } + y() { + } } class B extends A { // async method with only call/get on 'super' does not require a binding async simple() { const _super = null; + const _superIndex = null; // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -24,6 +29,7 @@ class B extends A { // async method with assignment/destructuring on 'super' requires a binding async advanced() { const _super = null; + const _superIndex = null; const f = () => {}; // call with property access @@ -50,7 +56,8 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} +} + //// [asyncMethodWithSuperConflict_es6.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { @@ -64,48 +71,61 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge class A { x() { } + y() { + } } class B extends A { // async method with only call/get on 'super' does not require a binding simple() { - const _super_1 = name => super[name]; + const _superIndex_1 = name => super[name]; + const _super_1 = Object.create(null, { + x: { get: () => super.x }, + y: { get: () => super.y } + }); return __awaiter(this, void 0, void 0, function* () { const _super = null; + const _superIndex = null; // call with property access - _super_1("x").call(this); + _super_1.x.call(this); + // call additional property. + _super_1.y.call(this); // call with element access - _super_1("x").call(this); + _superIndex_1("x").call(this); // property access (read) - const a = _super_1("x"); + const a = _super_1.x; // element access (read) - const b = _super_1("x"); + const b = _superIndex_1("x"); }); } // async method with assignment/destructuring on 'super' requires a binding advanced() { - const _super_1 = (function (geti, seti) { + const _superIndex_1 = (function (geti, seti) { const cache = Object.create(null); return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); })(name => super[name], (name, value) => super[name] = value); + const _super_1 = Object.create(null, { + x: { get: () => super.x, set: v => super.x = v } + }); return __awaiter(this, void 0, void 0, function* () { const _super = null; + const _superIndex = null; const f = () => { }; // call with property access - _super_1("x").value.call(this); + _super_1.x.call(this); // call with element access - _super_1("x").value.call(this); + _superIndex_1("x").value.call(this); // property access (read) - const a = _super_1("x").value; + const a = _super_1.x; // element access (read) - const b = _super_1("x").value; + const b = _superIndex_1("x").value; // property access (assign) - _super_1("x").value = f; + _super_1.x = f; // element access (assign) - _super_1("x").value = f; + _superIndex_1("x").value = f; // destructuring assign with property access - ({ f: _super_1("x").value } = { f }); + ({ f: _super_1.x } = { f }); // destructuring assign with element access - ({ f: _super_1("x").value } = { f }); + ({ f: _superIndex_1("x").value } = { f }); }); } } diff --git a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.symbols b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.symbols index ddc8fdf013c..161b6eca39b 100644 --- a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.symbols +++ b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.symbols @@ -5,18 +5,24 @@ class A { x() { >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) } + y() { +>y : Symbol(A.y, Decl(asyncMethodWithSuperConflict_es6.ts, 2, 5)) + } } class B extends A { ->B : Symbol(B, Decl(asyncMethodWithSuperConflict_es6.ts, 3, 1)) +>B : Symbol(B, Decl(asyncMethodWithSuperConflict_es6.ts, 5, 1)) >A : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) // async method with only call/get on 'super' does not require a binding async simple() { ->simple : Symbol(B.simple, Decl(asyncMethodWithSuperConflict_es6.ts, 5, 19)) +>simple : Symbol(B.simple, Decl(asyncMethodWithSuperConflict_es6.ts, 7, 19)) const _super = null; ->_super : Symbol(_super, Decl(asyncMethodWithSuperConflict_es6.ts, 8, 13)) +>_super : Symbol(_super, Decl(asyncMethodWithSuperConflict_es6.ts, 10, 13)) + + const _superIndex = null; +>_superIndex : Symbol(_superIndex, Decl(asyncMethodWithSuperConflict_es6.ts, 11, 13)) // call with property access super.x(); @@ -24,6 +30,12 @@ class B extends A { >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) + // call additional property. + super.y(); +>super.y : Symbol(A.y, Decl(asyncMethodWithSuperConflict_es6.ts, 2, 5)) +>super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) +>y : Symbol(A.y, Decl(asyncMethodWithSuperConflict_es6.ts, 2, 5)) + // call with element access super["x"](); >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) @@ -31,27 +43,30 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuperConflict_es6.ts, 16, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuperConflict_es6.ts, 21, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuperConflict_es6.ts, 19, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuperConflict_es6.ts, 24, 13)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) } // async method with assignment/destructuring on 'super' requires a binding async advanced() { ->advanced : Symbol(B.advanced, Decl(asyncMethodWithSuperConflict_es6.ts, 20, 5)) +>advanced : Symbol(B.advanced, Decl(asyncMethodWithSuperConflict_es6.ts, 25, 5)) const _super = null; ->_super : Symbol(_super, Decl(asyncMethodWithSuperConflict_es6.ts, 24, 13)) +>_super : Symbol(_super, Decl(asyncMethodWithSuperConflict_es6.ts, 29, 13)) + + const _superIndex = null; +>_superIndex : Symbol(_superIndex, Decl(asyncMethodWithSuperConflict_es6.ts, 30, 13)) const f = () => {}; ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 25, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 31, 13)) // call with property access super.x(); @@ -66,14 +81,14 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuperConflict_es6.ts, 34, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuperConflict_es6.ts, 40, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuperConflict_es6.ts, 37, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuperConflict_es6.ts, 43, 13)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) @@ -82,27 +97,28 @@ class B extends A { >super.x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 25, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 31, 13)) // element access (assign) super["x"] = f; >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 25, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 31, 13)) // destructuring assign with property access ({ f: super.x } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 46, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 52, 10)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 46, 27)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 52, 27)) // destructuring assign with element access ({ f: super["x"] } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 49, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 55, 10)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 49, 30)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 55, 30)) } } + diff --git a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.types b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.types index ac82440a3d8..9efebc2f192 100644 --- a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.types +++ b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.types @@ -5,6 +5,9 @@ class A { x() { >x : () => void } + y() { +>y : () => void + } } class B extends A { @@ -17,6 +20,10 @@ class B extends A { const _super = null; >_super : any +>null : null + + const _superIndex = null; +>_superIndex : any >null : null // call with property access @@ -26,6 +33,13 @@ class B extends A { >super : A >x : () => void + // call additional property. + super.y(); +>super.y() : void +>super.y : () => void +>super : A +>y : () => void + // call with element access super["x"](); >super["x"]() : void @@ -54,6 +68,10 @@ class B extends A { const _super = null; >_super : any +>null : null + + const _superIndex = null; +>_superIndex : any >null : null const f = () => {}; @@ -129,3 +147,4 @@ class B extends A { >f : () => void } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.js b/tests/baselines/reference/asyncMethodWithSuper_es2017.js index b6925793163..4c5a7aa9866 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es2017.js +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.js @@ -2,6 +2,8 @@ class A { x() { } + y() { + } } class B extends A { @@ -9,6 +11,8 @@ class B extends A { async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -48,18 +52,23 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} +} + //// [asyncMethodWithSuper_es2017.js] class A { x() { } + y() { + } } class B extends A { // async method with only call/get on 'super' does not require a binding async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); // property access (read) diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols b/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols index 39ed91d7acb..bee97d8a006 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols @@ -5,15 +5,18 @@ class A { x() { >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) } + y() { +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es2017.ts, 2, 5)) + } } class B extends A { ->B : Symbol(B, Decl(asyncMethodWithSuper_es2017.ts, 3, 1)) +>B : Symbol(B, Decl(asyncMethodWithSuper_es2017.ts, 5, 1)) >A : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) // async method with only call/get on 'super' does not require a binding async simple() { ->simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es2017.ts, 5, 19)) +>simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es2017.ts, 7, 19)) // call with property access super.x(); @@ -21,6 +24,12 @@ class B extends A { >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + // call additional property. + super.y(); +>super.y : Symbol(A.y, Decl(asyncMethodWithSuper_es2017.ts, 2, 5)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es2017.ts, 2, 5)) + // call with element access super["x"](); >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) @@ -28,24 +37,24 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 15, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 19, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 18, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 22, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) } // async method with assignment/destructuring on 'super' requires a binding async advanced() { ->advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es2017.ts, 19, 5)) +>advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es2017.ts, 23, 5)) const f = () => {}; ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 27, 13)) // call with property access super.x(); @@ -60,14 +69,14 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 32, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 36, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 35, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 39, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) @@ -76,27 +85,28 @@ class B extends A { >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 27, 13)) // element access (assign) super["x"] = f; >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 27, 13)) // destructuring assign with property access ({ f: super.x } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 44, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 48, 10)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 44, 27)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 48, 27)) // destructuring assign with element access ({ f: super["x"] } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 47, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 51, 10)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 47, 30)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 51, 30)) } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.types b/tests/baselines/reference/asyncMethodWithSuper_es2017.types index b2678e8b837..b76b13798b8 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es2017.types +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.types @@ -5,6 +5,9 @@ class A { x() { >x : () => void } + y() { +>y : () => void + } } class B extends A { @@ -22,6 +25,13 @@ class B extends A { >super : A >x : () => void + // call additional property. + super.y(); +>super.y() : void +>super.y : () => void +>super : A +>y : () => void + // call with element access super["x"](); >super["x"]() : void @@ -121,3 +131,4 @@ class B extends A { >f : () => void } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es5.js b/tests/baselines/reference/asyncMethodWithSuper_es5.js index a2931b9f8e1..441ad8875c4 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es5.js +++ b/tests/baselines/reference/asyncMethodWithSuper_es5.js @@ -2,6 +2,8 @@ class A { x() { } + y() { + } } class B extends A { @@ -9,6 +11,8 @@ class B extends A { async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -48,7 +52,8 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} +} + //// [asyncMethodWithSuper_es5.js] var A = /** @class */ (function () { @@ -56,6 +61,8 @@ var A = /** @class */ (function () { } A.prototype.x = function () { }; + A.prototype.y = function () { + }; return A; }()); var B = /** @class */ (function (_super) { @@ -70,6 +77,8 @@ var B = /** @class */ (function (_super) { return __generator(this, function (_a) { // call with property access _super.prototype.x.call(this); + // call additional property. + _super.prototype.y.call(this); // call with element access _super.prototype["x"].call(this); a = _super.prototype.x; diff --git a/tests/baselines/reference/asyncMethodWithSuper_es5.symbols b/tests/baselines/reference/asyncMethodWithSuper_es5.symbols index e05f00a8e97..c013058c85a 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es5.symbols +++ b/tests/baselines/reference/asyncMethodWithSuper_es5.symbols @@ -5,15 +5,18 @@ class A { x() { >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) } + y() { +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es5.ts, 2, 5)) + } } class B extends A { ->B : Symbol(B, Decl(asyncMethodWithSuper_es5.ts, 3, 1)) +>B : Symbol(B, Decl(asyncMethodWithSuper_es5.ts, 5, 1)) >A : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) // async method with only call/get on 'super' does not require a binding async simple() { ->simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es5.ts, 5, 19)) +>simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es5.ts, 7, 19)) // call with property access super.x(); @@ -21,6 +24,12 @@ class B extends A { >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) + // call additional property. + super.y(); +>super.y : Symbol(A.y, Decl(asyncMethodWithSuper_es5.ts, 2, 5)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es5.ts, 2, 5)) + // call with element access super["x"](); >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) @@ -28,24 +37,24 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es5.ts, 15, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es5.ts, 19, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es5.ts, 18, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es5.ts, 22, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) } // async method with assignment/destructuring on 'super' requires a binding async advanced() { ->advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es5.ts, 19, 5)) +>advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es5.ts, 23, 5)) const f = () => {}; ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 27, 13)) // call with property access super.x(); @@ -60,14 +69,14 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es5.ts, 32, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es5.ts, 36, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es5.ts, 35, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es5.ts, 39, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) @@ -76,27 +85,28 @@ class B extends A { >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 27, 13)) // element access (assign) super["x"] = f; >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 27, 13)) // destructuring assign with property access ({ f: super.x } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 44, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 48, 10)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 44, 27)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 48, 27)) // destructuring assign with element access ({ f: super["x"] } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 47, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 51, 10)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 47, 30)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 51, 30)) } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es5.types b/tests/baselines/reference/asyncMethodWithSuper_es5.types index 4622d83a679..58f545dc93b 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es5.types +++ b/tests/baselines/reference/asyncMethodWithSuper_es5.types @@ -5,6 +5,9 @@ class A { x() { >x : () => void } + y() { +>y : () => void + } } class B extends A { @@ -22,6 +25,13 @@ class B extends A { >super : A >x : () => void + // call additional property. + super.y(); +>super.y() : void +>super.y : () => void +>super : A +>y : () => void + // call with element access super["x"](); >super["x"]() : void @@ -121,3 +131,4 @@ class B extends A { >f : () => void } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es6.js b/tests/baselines/reference/asyncMethodWithSuper_es6.js index eacb0a882b2..5ff89d26e94 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es6.js +++ b/tests/baselines/reference/asyncMethodWithSuper_es6.js @@ -2,6 +2,8 @@ class A { x() { } + y() { + } } class B extends A { @@ -9,6 +11,8 @@ class B extends A { async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -48,52 +52,64 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} +} + //// [asyncMethodWithSuper_es6.js] class A { x() { } + y() { + } } class B extends A { // async method with only call/get on 'super' does not require a binding simple() { - const _super = name => super[name]; + const _superIndex = name => super[name]; + const _super = Object.create(null, { + x: { get: () => super.x }, + y: { get: () => super.y } + }); return __awaiter(this, void 0, void 0, function* () { // call with property access - _super("x").call(this); + _super.x.call(this); + // call additional property. + _super.y.call(this); // call with element access - _super("x").call(this); + _superIndex("x").call(this); // property access (read) - const a = _super("x"); + const a = _super.x; // element access (read) - const b = _super("x"); + const b = _superIndex("x"); }); } // async method with assignment/destructuring on 'super' requires a binding advanced() { - const _super = (function (geti, seti) { + const _superIndex = (function (geti, seti) { const cache = Object.create(null); return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); })(name => super[name], (name, value) => super[name] = value); + const _super = Object.create(null, { + x: { get: () => super.x, set: v => super.x = v } + }); return __awaiter(this, void 0, void 0, function* () { const f = () => { }; // call with property access - _super("x").value.call(this); + _super.x.call(this); // call with element access - _super("x").value.call(this); + _superIndex("x").value.call(this); // property access (read) - const a = _super("x").value; + const a = _super.x; // element access (read) - const b = _super("x").value; + const b = _superIndex("x").value; // property access (assign) - _super("x").value = f; + _super.x = f; // element access (assign) - _super("x").value = f; + _superIndex("x").value = f; // destructuring assign with property access - ({ f: _super("x").value } = { f }); + ({ f: _super.x } = { f }); // destructuring assign with element access - ({ f: _super("x").value } = { f }); + ({ f: _superIndex("x").value } = { f }); }); } } diff --git a/tests/baselines/reference/asyncMethodWithSuper_es6.symbols b/tests/baselines/reference/asyncMethodWithSuper_es6.symbols index 268ad90f203..d33bcf3449a 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es6.symbols +++ b/tests/baselines/reference/asyncMethodWithSuper_es6.symbols @@ -5,15 +5,18 @@ class A { x() { >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) } + y() { +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es6.ts, 2, 5)) + } } class B extends A { ->B : Symbol(B, Decl(asyncMethodWithSuper_es6.ts, 3, 1)) +>B : Symbol(B, Decl(asyncMethodWithSuper_es6.ts, 5, 1)) >A : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) // async method with only call/get on 'super' does not require a binding async simple() { ->simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es6.ts, 5, 19)) +>simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es6.ts, 7, 19)) // call with property access super.x(); @@ -21,6 +24,12 @@ class B extends A { >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) + // call additional property. + super.y(); +>super.y : Symbol(A.y, Decl(asyncMethodWithSuper_es6.ts, 2, 5)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es6.ts, 2, 5)) + // call with element access super["x"](); >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) @@ -28,24 +37,24 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es6.ts, 15, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es6.ts, 19, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es6.ts, 18, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es6.ts, 22, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) } // async method with assignment/destructuring on 'super' requires a binding async advanced() { ->advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es6.ts, 19, 5)) +>advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es6.ts, 23, 5)) const f = () => {}; ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 27, 13)) // call with property access super.x(); @@ -60,14 +69,14 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es6.ts, 32, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es6.ts, 36, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es6.ts, 35, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es6.ts, 39, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) @@ -76,27 +85,28 @@ class B extends A { >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 27, 13)) // element access (assign) super["x"] = f; >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 27, 13)) // destructuring assign with property access ({ f: super.x } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 44, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 48, 10)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 44, 27)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 48, 27)) // destructuring assign with element access ({ f: super["x"] } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 47, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 51, 10)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 47, 30)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 51, 30)) } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es6.types b/tests/baselines/reference/asyncMethodWithSuper_es6.types index 030c9fe4e6a..1333beb8f04 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es6.types +++ b/tests/baselines/reference/asyncMethodWithSuper_es6.types @@ -5,6 +5,9 @@ class A { x() { >x : () => void } + y() { +>y : () => void + } } class B extends A { @@ -22,6 +25,13 @@ class B extends A { >super : A >x : () => void + // call additional property. + super.y(); +>super.y() : void +>super.y : () => void +>super : A +>y : () => void + // call with element access super["x"](); >super["x"]() : void @@ -121,3 +131,4 @@ class B extends A { >f : () => void } } + diff --git a/tests/baselines/reference/augmentExportEquals3.symbols b/tests/baselines/reference/augmentExportEquals3.symbols index e4e7a8e1a5f..2644d6d5b21 100644 --- a/tests/baselines/reference/augmentExportEquals3.symbols +++ b/tests/baselines/reference/augmentExportEquals3.symbols @@ -1,9 +1,9 @@ === tests/cases/compiler/file1.ts === function foo() {} ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) export var v = 1; >v : Symbol(v, Decl(file1.ts, 2, 14)) diff --git a/tests/baselines/reference/augmentExportEquals3_1.symbols b/tests/baselines/reference/augmentExportEquals3_1.symbols index 2431b293dea..181ceb343b8 100644 --- a/tests/baselines/reference/augmentExportEquals3_1.symbols +++ b/tests/baselines/reference/augmentExportEquals3_1.symbols @@ -3,10 +3,10 @@ declare module "file1" { >"file1" : Symbol("file1", Decl(file1.d.ts, 0, 0)) function foo(): void; ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) export var v: number; >v : Symbol(v, Decl(file1.d.ts, 3, 18)) diff --git a/tests/baselines/reference/augmentExportEquals4.symbols b/tests/baselines/reference/augmentExportEquals4.symbols index f1f63762545..75da60335c3 100644 --- a/tests/baselines/reference/augmentExportEquals4.symbols +++ b/tests/baselines/reference/augmentExportEquals4.symbols @@ -1,9 +1,9 @@ === tests/cases/compiler/file1.ts === class foo {} ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) export var v = 1; >v : Symbol(v, Decl(file1.ts, 2, 14)) diff --git a/tests/baselines/reference/augmentExportEquals4_1.symbols b/tests/baselines/reference/augmentExportEquals4_1.symbols index d2a3c001825..97d115e453e 100644 --- a/tests/baselines/reference/augmentExportEquals4_1.symbols +++ b/tests/baselines/reference/augmentExportEquals4_1.symbols @@ -3,10 +3,10 @@ declare module "file1" { >"file1" : Symbol("file1", Decl(file1.d.ts, 0, 0)) class foo {} ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) export var v: number; >v : Symbol(v, Decl(file1.d.ts, 3, 18)) diff --git a/tests/baselines/reference/augmentExportEquals5.symbols b/tests/baselines/reference/augmentExportEquals5.symbols index 244073b6515..ef62f66817e 100644 --- a/tests/baselines/reference/augmentExportEquals5.symbols +++ b/tests/baselines/reference/augmentExportEquals5.symbols @@ -16,12 +16,12 @@ declare module "express" { >"express" : Symbol("express", Decl(express.d.ts, 4, 1)) function e(): e.Express; ->e : Symbol(e, Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) +>e : Symbol("tests/cases/compiler/express.d.ts", Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) >e : Symbol(e, Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28)) >Express : Symbol(Express, Decl(express.d.ts, 52, 9)) namespace e { ->e : Symbol(e, Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) +>e : Symbol("tests/cases/compiler/express.d.ts", Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) interface IRoute { >IRoute : Symbol(IRoute, Decl(express.d.ts, 8, 17)) diff --git a/tests/baselines/reference/augmentExportEquals6.symbols b/tests/baselines/reference/augmentExportEquals6.symbols index 2125b650464..72ef677c592 100644 --- a/tests/baselines/reference/augmentExportEquals6.symbols +++ b/tests/baselines/reference/augmentExportEquals6.symbols @@ -1,9 +1,9 @@ === tests/cases/compiler/file1.ts === class foo {} ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) namespace foo { ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) export class A {} >A : Symbol(A, Decl(file1.ts, 1, 15), Decl(file2.ts, 4, 26)) diff --git a/tests/baselines/reference/augmentExportEquals6_1.symbols b/tests/baselines/reference/augmentExportEquals6_1.symbols index b75f8131c01..e37b094549a 100644 --- a/tests/baselines/reference/augmentExportEquals6_1.symbols +++ b/tests/baselines/reference/augmentExportEquals6_1.symbols @@ -3,10 +3,10 @@ declare module "file1" { >"file1" : Symbol("file1", Decl(file1.d.ts, 0, 0)) class foo {} ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) namespace foo { ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) class A {} >A : Symbol(A, Decl(file1.d.ts, 2, 19), Decl(file2.ts, 4, 24)) diff --git a/tests/baselines/reference/autolift4.js b/tests/baselines/reference/autolift4.js index 19d6cd43932..53ce6dc9dc3 100644 --- a/tests/baselines/reference/autolift4.js +++ b/tests/baselines/reference/autolift4.js @@ -30,7 +30,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/bangInModuleName.symbols b/tests/baselines/reference/bangInModuleName.symbols index ca3d4a161f5..fa1b84ba296 100644 --- a/tests/baselines/reference/bangInModuleName.symbols +++ b/tests/baselines/reference/bangInModuleName.symbols @@ -10,7 +10,7 @@ declare module "http" { } declare module 'intern/dojo/node!http' { ->'intern/dojo/node!http' : Symbol('intern/dojo/node!http', Decl(a.d.ts, 1, 1)) +>'intern/dojo/node!http' : Symbol("intern/dojo/node!http", Decl(a.d.ts, 1, 1)) import http = require('http'); >http : Symbol(http, Decl(a.d.ts, 3, 40)) diff --git a/tests/baselines/reference/baseCheck.errors.txt b/tests/baselines/reference/baseCheck.errors.txt index ca99ca426fc..67358a10338 100644 --- a/tests/baselines/reference/baseCheck.errors.txt +++ b/tests/baselines/reference/baseCheck.errors.txt @@ -32,6 +32,7 @@ tests/cases/compiler/baseCheck.ts(26,9): error TS2304: Cannot find name 'x'. class D extends C { constructor(public z: number) { super(this.z) } } // too few params ~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/compiler/baseCheck.ts:1:34: An argument for 'y' was not provided. ~~~~ !!! error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. class E extends C { constructor(public z: number) { super(0, this.z) } } diff --git a/tests/baselines/reference/baseCheck.js b/tests/baselines/reference/baseCheck.js index e48c235a087..114bbf655e4 100644 --- a/tests/baselines/reference/baseCheck.js +++ b/tests/baselines/reference/baseCheck.js @@ -36,7 +36,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/baseClassImprovedMismatchErrors.js b/tests/baselines/reference/baseClassImprovedMismatchErrors.js index def62c018bd..2b864807570 100644 --- a/tests/baselines/reference/baseClassImprovedMismatchErrors.js +++ b/tests/baselines/reference/baseClassImprovedMismatchErrors.js @@ -25,7 +25,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/baseConstraintOfDecorator.js b/tests/baselines/reference/baseConstraintOfDecorator.js index 198dcb3d7b9..a7f6b6e41cb 100644 --- a/tests/baselines/reference/baseConstraintOfDecorator.js +++ b/tests/baselines/reference/baseConstraintOfDecorator.js @@ -17,7 +17,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/baseExpressionTypeParameters.js b/tests/baselines/reference/baseExpressionTypeParameters.js index fd907be7e52..aa16fcebf55 100644 --- a/tests/baselines/reference/baseExpressionTypeParameters.js +++ b/tests/baselines/reference/baseExpressionTypeParameters.js @@ -21,7 +21,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/baseIndexSignatureResolution.js b/tests/baselines/reference/baseIndexSignatureResolution.js index d5732b7f3d5..09aabe21ac4 100644 --- a/tests/baselines/reference/baseIndexSignatureResolution.js +++ b/tests/baselines/reference/baseIndexSignatureResolution.js @@ -31,7 +31,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/baseTypeOrderChecking.js b/tests/baselines/reference/baseTypeOrderChecking.js index 9e6800d376a..31fa3391af5 100644 --- a/tests/baselines/reference/baseTypeOrderChecking.js +++ b/tests/baselines/reference/baseTypeOrderChecking.js @@ -43,7 +43,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/baseTypeWrappingInstantiationChain.js b/tests/baselines/reference/baseTypeWrappingInstantiationChain.js index 3f8e475504d..de50a58205d 100644 --- a/tests/baselines/reference/baseTypeWrappingInstantiationChain.js +++ b/tests/baselines/reference/baseTypeWrappingInstantiationChain.js @@ -34,7 +34,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/bases.js b/tests/baselines/reference/bases.js index 9ff19e7ae61..25cf4073d5c 100644 --- a/tests/baselines/reference/bases.js +++ b/tests/baselines/reference/bases.js @@ -27,7 +27,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js index 1eaa060ce1f..b755bf200a5 100644 --- a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js +++ b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js @@ -35,7 +35,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js index 77543b29fe8..b7afc3eee41 100644 --- a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js +++ b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js @@ -33,7 +33,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt b/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt index 2c57099c3e8..e3c5dcc7986 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt +++ b/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(22,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(23,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(24,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(25,13): error TS2733: Index '3' is out-of-bounds in tuple of length 3. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(22,13): error TS2339: Property '2' does not exist on type '[(x: number) => string, (x: number) => number]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(23,13): error TS2339: Property '2' does not exist on type '[E1, E2]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(24,13): error TS2339: Property '2' does not exist on type '[number, any]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(25,13): error TS2339: Property '3' does not exist on type '[E1, E2, number]'. ==== tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts (4 errors) ==== @@ -28,13 +28,13 @@ tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfT t4 = [E1.one, E2.two, 20]; var e1 = t1[2]; // {} ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[(x: number) => string, (x: number) => number]'. var e2 = t2[2]; // {} ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[E1, E2]'. var e3 = t3[2]; // any ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, any]'. var e4 = t4[3]; // number ~ -!!! error TS2733: Index '3' is out-of-bounds in tuple of length 3. \ No newline at end of file +!!! error TS2339: Property '3' does not exist on type '[E1, E2, number]'. \ No newline at end of file diff --git a/tests/baselines/reference/bestCommonTypeOfTuple.types b/tests/baselines/reference/bestCommonTypeOfTuple.types index 612403084a5..4cc64a25505 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple.types +++ b/tests/baselines/reference/bestCommonTypeOfTuple.types @@ -76,26 +76,26 @@ t4 = [E1.one, E2.two, 20]; >20 : 20 var e1 = t1[2]; // {} ->e1 : ((x: number) => string) | ((x: number) => number) ->t1[2] : ((x: number) => string) | ((x: number) => number) +>e1 : undefined +>t1[2] : undefined >t1 : [(x: number) => string, (x: number) => number] >2 : 2 var e2 = t2[2]; // {} ->e2 : E1 | E2 ->t2[2] : E1 | E2 +>e2 : undefined +>t2[2] : undefined >t2 : [E1, E2] >2 : 2 var e3 = t3[2]; // any ->e3 : any ->t3[2] : any +>e3 : undefined +>t3[2] : undefined >t3 : [number, any] >2 : 2 var e4 = t4[3]; // number ->e4 : number ->t4[3] : number +>e4 : undefined +>t4[3] : undefined >t4 : [E1, E2, number] >3 : 3 diff --git a/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt b/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt index 80f40c74a07..d2fd301e131 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt +++ b/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(17,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(18,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(19,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(20,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(21,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(17,14): error TS2339: Property '4' does not exist on type '[C, base]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(18,14): error TS2339: Property '4' does not exist on type '[C, D]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(19,14): error TS2339: Property '4' does not exist on type '[C1, D1]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(20,14): error TS2339: Property '2' does not exist on type '[base1, C1]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(21,14): error TS2339: Property '2' does not exist on type '[C1, F]'. ==== tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts (5 errors) ==== @@ -24,17 +24,17 @@ tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfT var e11 = t1[4]; // base ~ -!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '4' does not exist on type '[C, base]'. var e21 = t2[4]; // {} ~ -!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '4' does not exist on type '[C, D]'. var e31 = t3[4]; // C1 ~ -!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '4' does not exist on type '[C1, D1]'. var e41 = t4[2]; // base1 ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[base1, C1]'. var e51 = t5[2]; // {} ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[C1, F]'. \ No newline at end of file diff --git a/tests/baselines/reference/bestCommonTypeOfTuple2.js b/tests/baselines/reference/bestCommonTypeOfTuple2.js index 0dbea701fa3..a3672a76423 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple2.js +++ b/tests/baselines/reference/bestCommonTypeOfTuple2.js @@ -29,7 +29,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/bestCommonTypeOfTuple2.types b/tests/baselines/reference/bestCommonTypeOfTuple2.types index 33691bc65a9..6b3e6a3789c 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple2.types +++ b/tests/baselines/reference/bestCommonTypeOfTuple2.types @@ -49,32 +49,32 @@ var t5: [C1, F] >t5 : [C1, F] var e11 = t1[4]; // base ->e11 : base | C ->t1[4] : base | C +>e11 : undefined +>t1[4] : undefined >t1 : [C, base] >4 : 4 var e21 = t2[4]; // {} ->e21 : C | D ->t2[4] : C | D +>e21 : undefined +>t2[4] : undefined >t2 : [C, D] >4 : 4 var e31 = t3[4]; // C1 ->e31 : C1 | D1 ->t3[4] : C1 | D1 +>e31 : undefined +>t3[4] : undefined >t3 : [C1, D1] >4 : 4 var e41 = t4[2]; // base1 ->e41 : base1 | C1 ->t4[2] : base1 | C1 +>e41 : undefined +>t4[2] : undefined >t4 : [base1, C1] >2 : 2 var e51 = t5[2]; // {} ->e51 : F | C1 ->t5[2] : F | C1 +>e51 : undefined +>t5[2] : undefined >t5 : [C1, F] >2 : 2 diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt new file mode 100644 index 00000000000..023e40a70da --- /dev/null +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt @@ -0,0 +1,39 @@ +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(3,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(5,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(7,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(10,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(13,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + + +==== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts (5 errors) ==== + declare function foo(): string; + + foo()(1 as number).toString(); + ~~~~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + + foo() (1 as number).toString(); + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + + foo() + ~~~~~ + (1 as number).toString(); + ~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:7:1: It is highly likely that you are missing a semicolon. + + foo() + ~~~~~~~~ + (1 as number).toString(); + ~~~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:10:1: It is highly likely that you are missing a semicolon. + + foo() + ~~~~~~~~ + (1).toString(); + ~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:13:1: It is highly likely that you are missing a semicolon. + \ No newline at end of file diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js new file mode 100644 index 00000000000..877ed539e71 --- /dev/null +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js @@ -0,0 +1,23 @@ +//// [betterErrorForAccidentallyCallingTypeAssertionExpressions.ts] +declare function foo(): string; + +foo()(1 as number).toString(); + +foo() (1 as number).toString(); + +foo() +(1 as number).toString(); + +foo() + (1 as number).toString(); + +foo() + (1).toString(); + + +//// [betterErrorForAccidentallyCallingTypeAssertionExpressions.js] +foo()(1).toString(); +foo()(1).toString(); +foo()(1).toString(); +foo()(1).toString(); +foo()(1).toString(); diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols new file mode 100644 index 00000000000..9dc2e676937 --- /dev/null +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols @@ -0,0 +1,25 @@ +=== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts === +declare function foo(): string; +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + +foo()(1 as number).toString(); +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + +foo() (1 as number).toString(); +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + +foo() +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + +(1 as number).toString(); + +foo() +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + + (1 as number).toString(); + +foo() +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + + (1).toString(); + diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types new file mode 100644 index 00000000000..54564d7462c --- /dev/null +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types @@ -0,0 +1,60 @@ +=== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts === +declare function foo(): string; +>foo : () => string + +foo()(1 as number).toString(); +>foo()(1 as number).toString() : any +>foo()(1 as number).toString : any +>foo()(1 as number) : any +>foo() : string +>foo : () => string +>1 as number : number +>1 : 1 +>toString : any + +foo() (1 as number).toString(); +>foo() (1 as number).toString() : any +>foo() (1 as number).toString : any +>foo() (1 as number) : any +>foo() : string +>foo : () => string +>1 as number : number +>1 : 1 +>toString : any + +foo() +>foo()(1 as number).toString() : any +>foo()(1 as number).toString : any +>foo()(1 as number) : any +>foo() : string +>foo : () => string + +(1 as number).toString(); +>1 as number : number +>1 : 1 +>toString : any + +foo() +>foo() (1 as number).toString() : any +>foo() (1 as number).toString : any +>foo() (1 as number) : any +>foo() : string +>foo : () => string + + (1 as number).toString(); +>1 as number : number +>1 : 1 +>toString : any + +foo() +>foo() (1).toString() : any +>foo() (1).toString : any +>foo() (1) : any +>foo() : string +>foo : () => string + + (1).toString(); +>1 : number +>1 : 1 +>toString : any + diff --git a/tests/baselines/reference/bivariantInferences.js b/tests/baselines/reference/bivariantInferences.js new file mode 100644 index 00000000000..a910ca15e93 --- /dev/null +++ b/tests/baselines/reference/bivariantInferences.js @@ -0,0 +1,17 @@ +//// [bivariantInferences.ts] +// Repro from #27337 + +interface Array { + equalsShallow(this: ReadonlyArray, other: ReadonlyArray): boolean; +} + +declare const a: (string | number)[] | null[] | undefined[] | {}[]; +declare const b: (string | number)[] | null[] | undefined[] | {}[]; + +let x = a.equalsShallow(b); + + +//// [bivariantInferences.js] +"use strict"; +// Repro from #27337 +var x = a.equalsShallow(b); diff --git a/tests/baselines/reference/bivariantInferences.symbols b/tests/baselines/reference/bivariantInferences.symbols new file mode 100644 index 00000000000..63cc239f040 --- /dev/null +++ b/tests/baselines/reference/bivariantInferences.symbols @@ -0,0 +1,31 @@ +=== tests/cases/conformance/types/typeRelationships/typeInference/bivariantInferences.ts === +// Repro from #27337 + +interface Array { +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(bivariantInferences.ts, 0, 0)) +>T : Symbol(T, Decl(lib.es5.d.ts, --, --), Decl(bivariantInferences.ts, 2, 16)) + + equalsShallow(this: ReadonlyArray, other: ReadonlyArray): boolean; +>equalsShallow : Symbol(Array.equalsShallow, Decl(bivariantInferences.ts, 2, 20)) +>T : Symbol(T, Decl(bivariantInferences.ts, 3, 18)) +>this : Symbol(this, Decl(bivariantInferences.ts, 3, 21)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(bivariantInferences.ts, 3, 18)) +>other : Symbol(other, Decl(bivariantInferences.ts, 3, 44)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(bivariantInferences.ts, 3, 18)) +} + +declare const a: (string | number)[] | null[] | undefined[] | {}[]; +>a : Symbol(a, Decl(bivariantInferences.ts, 6, 13)) + +declare const b: (string | number)[] | null[] | undefined[] | {}[]; +>b : Symbol(b, Decl(bivariantInferences.ts, 7, 13)) + +let x = a.equalsShallow(b); +>x : Symbol(x, Decl(bivariantInferences.ts, 9, 3)) +>a.equalsShallow : Symbol(equalsShallow, Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20)) +>a : Symbol(a, Decl(bivariantInferences.ts, 6, 13)) +>equalsShallow : Symbol(equalsShallow, Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20)) +>b : Symbol(b, Decl(bivariantInferences.ts, 7, 13)) + diff --git a/tests/baselines/reference/bivariantInferences.types b/tests/baselines/reference/bivariantInferences.types new file mode 100644 index 00000000000..e9bf31dad8e --- /dev/null +++ b/tests/baselines/reference/bivariantInferences.types @@ -0,0 +1,26 @@ +=== tests/cases/conformance/types/typeRelationships/typeInference/bivariantInferences.ts === +// Repro from #27337 + +interface Array { + equalsShallow(this: ReadonlyArray, other: ReadonlyArray): boolean; +>equalsShallow : (this: ReadonlyArray, other: ReadonlyArray) => boolean +>this : ReadonlyArray +>other : ReadonlyArray +} + +declare const a: (string | number)[] | null[] | undefined[] | {}[]; +>a : (string | number)[] | null[] | undefined[] | {}[] +>null : null + +declare const b: (string | number)[] | null[] | undefined[] | {}[]; +>b : (string | number)[] | null[] | undefined[] | {}[] +>null : null + +let x = a.equalsShallow(b); +>x : boolean +>a.equalsShallow(b) : boolean +>a.equalsShallow : ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) +>a : (string | number)[] | null[] | undefined[] | {}[] +>equalsShallow : ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) +>b : (string | number)[] | null[] | undefined[] | {}[] + diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt index 77dc618f912..c9f636a7914 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt @@ -34,4 +34,5 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error T foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts:1:14: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt index c9a8c67296a..755bf4e9750 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt @@ -34,4 +34,5 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error T foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts:1:14: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt index fb53f7a8f96..e8c41aea290 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt @@ -31,8 +31,10 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): e foo(); // not ok - needs number ~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts:2:14: An argument for 'a' was not provided. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts:2:14: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt index ae2bdcf587f..fe208689c00 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt @@ -25,8 +25,10 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): e foo(); // not ok ~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts:2:14: An argument for 'a' was not provided. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts:2:14: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/booleanLiteralTypes1.types b/tests/baselines/reference/booleanLiteralTypes1.types index 8cd0a4331a7..c50ee4ab0ad 100644 --- a/tests/baselines/reference/booleanLiteralTypes1.types +++ b/tests/baselines/reference/booleanLiteralTypes1.types @@ -82,13 +82,13 @@ function f4(t: true, f: false) { >false : false var x1 = t && f; ->x1 : boolean +>x1 : false >t && f : false >t : true >f : false var x2 = f && t; ->x2 : boolean +>x2 : false >f && t : false >f : false >t : true @@ -100,7 +100,7 @@ function f4(t: true, f: false) { >f : false var x4 = f || t; ->x4 : boolean +>x4 : true >f || t : true >f : false >t : true diff --git a/tests/baselines/reference/booleanLiteralTypes2.types b/tests/baselines/reference/booleanLiteralTypes2.types index 52e4d85e0bd..15c8f1e9c53 100644 --- a/tests/baselines/reference/booleanLiteralTypes2.types +++ b/tests/baselines/reference/booleanLiteralTypes2.types @@ -82,25 +82,25 @@ function f4(t: true, f: false) { >false : false var x1 = t && f; ->x1 : boolean +>x1 : false >t && f : false >t : true >f : false var x2 = f && t; ->x2 : boolean +>x2 : false >f && t : false >f : false >t : true var x3 = t || f; ->x3 : boolean +>x3 : true >t || f : true >t : true >f : false var x4 = f || t; ->x4 : boolean +>x4 : true >f || t : true >f : false >t : true diff --git a/tests/baselines/reference/booleanLiteralsContextuallyTypedFromUnion.errors.txt b/tests/baselines/reference/booleanLiteralsContextuallyTypedFromUnion.errors.txt new file mode 100644 index 00000000000..5b8fb9b0ea8 --- /dev/null +++ b/tests/baselines/reference/booleanLiteralsContextuallyTypedFromUnion.errors.txt @@ -0,0 +1,31 @@ +error TS2318: Cannot find global type 'CallableFunction'. +error TS2318: Cannot find global type 'NewableFunction'. + + +!!! error TS2318: Cannot find global type 'CallableFunction'. +!!! error TS2318: Cannot find global type 'NewableFunction'. +==== tests/cases/compiler/booleanLiteralsContextuallyTypedFromUnion.tsx (0 errors) ==== + interface A { isIt: true; text: string; } + interface B { isIt: false; value: number; } + type C = A | B; + const isIt = Math.random() > 0.5; + const c: C = isIt ? { isIt, text: 'hey' } : { isIt, value: 123 }; + const cc: C = isIt ? { isIt: isIt, text: 'hey' } : { isIt: isIt, value: 123 }; + + type ComponentProps = + | { + optionalBool: true; + mandatoryFn: () => void; + } + | { + optionalBool: false; + }; + + let Funk = (_props: ComponentProps) =>
Hello
; + + let Fail1 = () => { }} optionalBool={true} /> + let Fail2 = () => { }} optionalBool={true as true} /> + let True = true as true; + let Fail3 = () => { }} optionalBool={True} /> + let attrs2 = { optionalBool: true as true, mandatoryFn: () => { } } + let Success = () => \ No newline at end of file diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js index fe8f9330a5f..e139bcca598 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js @@ -77,7 +77,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js index 27112f8d3c3..b8a024a8a09 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js @@ -122,7 +122,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js index 0928f8ebc29..a969d77fb03 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js @@ -57,7 +57,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js index 9d7dbc9eab6..cf8889cbf27 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js @@ -57,7 +57,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js index aa189c78f8f..baa98cb72d5 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js @@ -60,7 +60,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/callWithSpread.js b/tests/baselines/reference/callWithSpread.js index 423721645ad..f8f1959d2bb 100644 --- a/tests/baselines/reference/callWithSpread.js +++ b/tests/baselines/reference/callWithSpread.js @@ -65,7 +65,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/callWithSpread2.errors.txt b/tests/baselines/reference/callWithSpread2.errors.txt index 4333571ebf8..127bf936920 100644 --- a/tests/baselines/reference/callWithSpread2.errors.txt +++ b/tests/baselines/reference/callWithSpread2.errors.txt @@ -68,9 +68,11 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(34,8): erro prefix(...ns) // required parameters are required ~~~~~~~~~~~~~ !!! error TS2556: Expected 1-3 arguments, but got 0 or more. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts:3:25: An argument for 's' was not provided. prefix(...mixed) ~~~~~~~~~~~~~~~~ !!! error TS2556: Expected 1-3 arguments, but got 0 or more. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts:3:25: An argument for 's' was not provided. prefix(...tuple) ~~~~~~~~ !!! error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js b/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js index 2b8eb4e62aa..dd433fc1db7 100644 --- a/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js +++ b/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js @@ -18,7 +18,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/captureThisInSuperCall.js b/tests/baselines/reference/captureThisInSuperCall.js index 9406feca945..919f8491114 100644 --- a/tests/baselines/reference/captureThisInSuperCall.js +++ b/tests/baselines/reference/captureThisInSuperCall.js @@ -15,7 +15,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/capturedLetConstInLoop1.js b/tests/baselines/reference/capturedLetConstInLoop1.js index 3c064059cb0..7acaf851cc2 100644 --- a/tests/baselines/reference/capturedLetConstInLoop1.js +++ b/tests/baselines/reference/capturedLetConstInLoop1.js @@ -1,4 +1,6 @@ //// [capturedLetConstInLoop1.ts] +declare function use(x: any): any; + //==== let for (let x in {}) { (function() { return x}); @@ -56,6 +58,19 @@ for (let y = 0; y < 1; ++y) { (() => x + y); } +for (let y = (use(() => y), 0); y < 1; ++y) { +} + +for (let y = 0; use(() => y), y < 1; ++y) { +} + +for (let y = 0; y < 1; use(() => y), ++y) { +} + +for (let y = (use(() => y), 0); use(() => y), y < 1; use(() => y), ++y) { + use(() => y); +} + //=========const for (const x in {}) { (function() { return x}); @@ -202,93 +217,145 @@ var _loop_10 = function (y) { for (var y = 0; y < 1; ++y) { _loop_10(y); } -var _loop_11 = function (x) { +var _loop_init_1 = function () { + var y = (use(function () { return y; }), 0); + out_y_1 = y; +}; +var out_y_1; +_loop_init_1(); +for (var y = out_y_1; y < 1; ++y) { +} +var _loop_11 = function (y) { + if (inc_1) + ++y; + else + inc_1 = true; + if (!(use(function () { return y; }), y < 1)) + return "break"; +}; +var inc_1 = false; +for (var y = 0;;) { + var state_1 = _loop_11(y); + if (state_1 === "break") + break; +} +var _loop_12 = function (y) { + if (inc_2) + use(function () { return y; }), ++y; + else + inc_2 = true; +}; +var inc_2 = false; +for (var y = 0; y < 1;) { + _loop_12(y); +} +var _loop_init_2 = function () { + var y = (use(function () { return y; }), 0); + out_y_2 = y; +}; +var _loop_13 = function (y) { + if (inc_3) + use(function () { return y; }), ++y; + else + inc_3 = true; + if (!(use(function () { return y; }), y < 1)) + return out_y_2 = y, "break"; + use(function () { return y; }); +}; +var out_y_2, inc_3 = false; +_loop_init_2(); +for (var y = out_y_2;;) { + var state_2 = _loop_13(y); + if (state_2 === "break") + break; +} +var _loop_14 = function (x) { (function () { return x; }); (function () { return x; }); }; //=========const for (var x in {}) { - _loop_11(x); + _loop_14(x); } -var _loop_12 = function (x) { +var _loop_15 = function (x) { (function () { return x; }); (function () { return x; }); }; for (var _b = 0, _c = []; _b < _c.length; _b++) { var x = _c[_b]; - _loop_12(x); + _loop_15(x); } -var _loop_13 = function (x) { +var _loop_16 = function (x) { (function () { return x; }); (function () { return x; }); }; for (var x = 0; x < 1;) { - _loop_13(x); + _loop_16(x); } -var _loop_14 = function () { +var _loop_17 = function () { var x = 1; (function () { return x; }); (function () { return x; }); }; while (1 === 1) { - _loop_14(); + _loop_17(); } -var _loop_15 = function () { +var _loop_18 = function () { var x = 1; (function () { return x; }); (function () { return x; }); }; do { - _loop_15(); + _loop_18(); } while (1 === 1); -var _loop_16 = function (y) { +var _loop_19 = function (y) { var x = 1; (function () { return x; }); (function () { return x; }); }; for (var y = 0; y < 1;) { - _loop_16(y); + _loop_19(y); } -var _loop_17 = function (x, y) { +var _loop_20 = function (x, y) { (function () { return x + y; }); (function () { return x + y; }); }; for (var x = 0, y = 1; x < 1;) { - _loop_17(x, y); + _loop_20(x, y); } -var _loop_18 = function () { +var _loop_21 = function () { var x = 1, y = 1; (function () { return x + y; }); (function () { return x + y; }); }; while (1 === 1) { - _loop_18(); + _loop_21(); } -var _loop_19 = function () { +var _loop_22 = function () { var x = 1, y = 1; (function () { return x + y; }); (function () { return x + y; }); }; do { - _loop_19(); + _loop_22(); } while (1 === 1); -var _loop_20 = function (y) { +var _loop_23 = function (y) { var x = 1; (function () { return x + y; }); (function () { return x + y; }); }; for (var y = 0; y < 1;) { - _loop_20(y); + _loop_23(y); } -var _loop_21 = function (sx) { +var _loop_24 = function (sx) { (function () { return sobj[sx]; }); }; for (var sx in sobj) { - _loop_21(sx); + _loop_24(sx); } -var _loop_22 = function (ix) { +var _loop_25 = function (ix) { (function () { return iobj[ix]; }); }; for (var ix in iobj) { - _loop_22(ix); + _loop_25(ix); } diff --git a/tests/baselines/reference/capturedLetConstInLoop1.symbols b/tests/baselines/reference/capturedLetConstInLoop1.symbols index afa7898a258..43f263bd73a 100644 --- a/tests/baselines/reference/capturedLetConstInLoop1.symbols +++ b/tests/baselines/reference/capturedLetConstInLoop1.symbols @@ -1,286 +1,330 @@ === tests/cases/compiler/capturedLetConstInLoop1.ts === +declare function use(x: any): any; +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 0, 21)) + //==== let for (let x in {}) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 1, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 3, 8)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 1, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 3, 8)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 1, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 3, 8)) } for (let x of []) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 6, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 8, 8)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 6, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 8, 8)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 6, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 8, 8)) } for (let x = 0; x < 1; ++x) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 11, 8)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 11, 8)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 11, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 13, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 13, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 13, 8)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 11, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 13, 8)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 11, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 13, 8)) } while (1 === 1) { let x; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 17, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 19, 7)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 17, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 19, 7)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 17, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 19, 7)) } do { let x; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 23, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 25, 7)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 23, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 25, 7)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 23, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 25, 7)) } while (1 === 1) for (let y = 0; y < 1; ++y) { ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 28, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 28, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 28, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 30, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 30, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 30, 8)) let x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 29, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 31, 7)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 29, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 31, 7)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 29, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 31, 7)) } for (let x = 0, y = 1; x < 1; ++x) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 34, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 34, 15)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 34, 8)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 34, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 36, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 36, 15)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 36, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 36, 8)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 34, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 34, 15)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 36, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 36, 15)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 34, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 34, 15)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 36, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 36, 15)) } while (1 === 1) { let x, y; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 40, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 40, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 42, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 42, 10)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 40, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 40, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 42, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 42, 10)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 40, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 40, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 42, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 42, 10)) } do { let x, y; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 46, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 46, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 48, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 48, 10)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 46, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 46, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 48, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 48, 10)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 46, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 46, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 48, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 48, 10)) } while (1 === 1) for (let y = 0; y < 1; ++y) { ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 51, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 51, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 51, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 53, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 53, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 53, 8)) let x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 52, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 54, 7)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 52, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 51, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 54, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 53, 8)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 52, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 51, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 54, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 53, 8)) +} + +for (let y = (use(() => y), 0); y < 1; ++y) { +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 59, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 59, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 59, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 59, 8)) +} + +for (let y = 0; use(() => y), y < 1; ++y) { +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 62, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 62, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 62, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 62, 8)) +} + +for (let y = 0; y < 1; use(() => y), ++y) { +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 65, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 65, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 65, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 65, 8)) +} + +for (let y = (use(() => y), 0); use(() => y), y < 1; use(() => y), ++y) { +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) + + use(() => y); +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) } //=========const for (const x in {}) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 58, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 73, 10)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 58, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 73, 10)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 58, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 73, 10)) } for (const x of []) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 63, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 78, 10)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 63, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 78, 10)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 63, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 78, 10)) } for (const x = 0; x < 1;) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 68, 10)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 68, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 83, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 83, 10)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 68, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 83, 10)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 68, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 83, 10)) } while (1 === 1) { const x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 74, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 89, 9)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 74, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 89, 9)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 74, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 89, 9)) } do { const x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 80, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 95, 9)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 80, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 95, 9)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 80, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 95, 9)) } while (1 === 1) for (const y = 0; y < 1;) { ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 85, 10)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 85, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 100, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 100, 10)) const x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 86, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 101, 9)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 86, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 101, 9)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 86, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 101, 9)) } for (const x = 0, y = 1; x < 1;) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 91, 10)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 91, 17)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 91, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 106, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 106, 17)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 106, 10)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 91, 10)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 91, 17)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 106, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 106, 17)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 91, 10)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 91, 17)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 106, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 106, 17)) } while (1 === 1) { const x = 1, y = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 97, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 97, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 112, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 112, 16)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 97, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 97, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 112, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 112, 16)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 97, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 97, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 112, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 112, 16)) } do { const x = 1, y = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 103, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 103, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 118, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 118, 16)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 103, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 103, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 118, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 118, 16)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 103, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 103, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 118, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 118, 16)) } while (1 === 1) for (const y = 0; y < 1;) { ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 108, 10)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 108, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 123, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 123, 10)) const x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 109, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 124, 9)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 109, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 108, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 124, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 123, 10)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 109, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 108, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 124, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 123, 10)) } // https://github.com/Microsoft/TypeScript/issues/20594 declare const sobj: { [x: string]: any }; ->sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 115, 13)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 115, 23)) +>sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 130, 13)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 130, 23)) for (let sx in sobj) { ->sx : Symbol(sx, Decl(capturedLetConstInLoop1.ts, 116, 8)) ->sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 115, 13)) +>sx : Symbol(sx, Decl(capturedLetConstInLoop1.ts, 131, 8)) +>sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 130, 13)) (() => sobj[sx]); ->sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 115, 13)) ->sx : Symbol(sx, Decl(capturedLetConstInLoop1.ts, 116, 8)) +>sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 130, 13)) +>sx : Symbol(sx, Decl(capturedLetConstInLoop1.ts, 131, 8)) } declare const iobj: { [x: number]: any }; ->iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 119, 13)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 119, 23)) +>iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 134, 13)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 134, 23)) for (let ix in iobj) { ->ix : Symbol(ix, Decl(capturedLetConstInLoop1.ts, 120, 8)) ->iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 119, 13)) +>ix : Symbol(ix, Decl(capturedLetConstInLoop1.ts, 135, 8)) +>iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 134, 13)) (() => iobj[ix]); ->iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 119, 13)) ->ix : Symbol(ix, Decl(capturedLetConstInLoop1.ts, 120, 8)) +>iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 134, 13)) +>ix : Symbol(ix, Decl(capturedLetConstInLoop1.ts, 135, 8)) } diff --git a/tests/baselines/reference/capturedLetConstInLoop1.types b/tests/baselines/reference/capturedLetConstInLoop1.types index 34ba101752b..a7d3094268c 100644 --- a/tests/baselines/reference/capturedLetConstInLoop1.types +++ b/tests/baselines/reference/capturedLetConstInLoop1.types @@ -1,4 +1,8 @@ === tests/cases/compiler/capturedLetConstInLoop1.ts === +declare function use(x: any): any; +>use : (x: any) => any +>x : any + //==== let for (let x in {}) { >x : string @@ -214,6 +218,84 @@ for (let y = 0; y < 1; ++y) { >y : number } +for (let y = (use(() => y), 0); y < 1; ++y) { +>y : number +>(use(() => y), 0) : 0 +>use(() => y), 0 : 0 +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>0 : 0 +>y < 1 : boolean +>y : number +>1 : 1 +>++y : number +>y : number +} + +for (let y = 0; use(() => y), y < 1; ++y) { +>y : number +>0 : 0 +>use(() => y), y < 1 : boolean +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>y < 1 : boolean +>y : number +>1 : 1 +>++y : number +>y : number +} + +for (let y = 0; y < 1; use(() => y), ++y) { +>y : number +>0 : 0 +>y < 1 : boolean +>y : number +>1 : 1 +>use(() => y), ++y : number +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>++y : number +>y : number +} + +for (let y = (use(() => y), 0); use(() => y), y < 1; use(() => y), ++y) { +>y : number +>(use(() => y), 0) : 0 +>use(() => y), 0 : 0 +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>0 : 0 +>use(() => y), y < 1 : boolean +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>y < 1 : boolean +>y : number +>1 : 1 +>use(() => y), ++y : number +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>++y : number +>y : number + + use(() => y); +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +} + //=========const for (const x in {}) { >x : string diff --git a/tests/baselines/reference/castingTuple.errors.txt b/tests/baselines/reference/castingTuple.errors.txt index e8bc9133a8a..08e2b32a858 100644 --- a/tests/baselines/reference/castingTuple.errors.txt +++ b/tests/baselines/reference/castingTuple.errors.txt @@ -6,7 +6,7 @@ tests/cases/conformance/types/tuple/castingTuple.ts(14,15): error TS2352: Conver tests/cases/conformance/types/tuple/castingTuple.ts(15,14): error TS2352: Conversion of type '[number, string]' to type '[number, string, boolean]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. tests/cases/conformance/types/tuple/castingTuple.ts(18,21): error TS2352: Conversion of type '[C, D]' to type '[C, D, A]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property '2' is missing in type '[C, D]'. -tests/cases/conformance/types/tuple/castingTuple.ts(20,33): error TS2733: Index '5' is out-of-bounds in tuple of length 3. +tests/cases/conformance/types/tuple/castingTuple.ts(20,33): error TS2339: Property '5' does not exist on type '[C, D, A]'. tests/cases/conformance/types/tuple/castingTuple.ts(30,10): error TS2352: Conversion of type '[number, string]' to type '[number, number]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type 'string' is not comparable to type 'number'. tests/cases/conformance/types/tuple/castingTuple.ts(31,10): error TS2352: Conversion of type '[C, D]' to type '[A, I]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. @@ -50,7 +50,7 @@ tests/cases/conformance/types/tuple/castingTuple.ts(33,1): error TS2304: Cannot var eleFromCDA1 = classCDATuple[2]; // A var eleFromCDA2 = classCDATuple[5]; // C | D | A ~ -!!! error TS2733: Index '5' is out-of-bounds in tuple of length 3. +!!! error TS2339: Property '5' does not exist on type '[C, D, A]'. var t10: [E1, E2] = [E1.one, E2.one]; var t11 = <[number, number]>t10; var array1 = <{}[]>emptyObjTuple; diff --git a/tests/baselines/reference/castingTuple.js b/tests/baselines/reference/castingTuple.js index 4bb4f5f788b..ac21b229a3c 100644 --- a/tests/baselines/reference/castingTuple.js +++ b/tests/baselines/reference/castingTuple.js @@ -41,7 +41,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/castingTuple.types b/tests/baselines/reference/castingTuple.types index 729c090e1ca..0c20dadc2be 100644 --- a/tests/baselines/reference/castingTuple.types +++ b/tests/baselines/reference/castingTuple.types @@ -83,8 +83,8 @@ var eleFromCDA1 = classCDATuple[2]; // A >2 : 2 var eleFromCDA2 = classCDATuple[5]; // C | D | A ->eleFromCDA2 : A | C | D ->classCDATuple[5] : A | C | D +>eleFromCDA2 : undefined +>classCDATuple[5] : undefined >classCDATuple : [C, D, A] >5 : 5 diff --git a/tests/baselines/reference/chainedAssignment3.js b/tests/baselines/reference/chainedAssignment3.js index acb96e5b9cf..c3e73310188 100644 --- a/tests/baselines/reference/chainedAssignment3.js +++ b/tests/baselines/reference/chainedAssignment3.js @@ -29,7 +29,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.errors.txt b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.errors.txt index 181bfcc907d..cee9236d630 100644 --- a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.errors.txt +++ b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.errors.txt @@ -1,6 +1,5 @@ -tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.ts(19,59): error TS2345: Argument of type '(c: C) => B' is not assignable to parameter of type '(x: C) => C'. - Type 'B' is not assignable to type 'C'. - Property 'z' is missing in type 'B'. +tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.ts(19,64): error TS2322: Type 'B' is not assignable to type 'C'. + Property 'z' is missing in type 'B'. ==== tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.ts (1 errors) ==== @@ -23,7 +22,7 @@ tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParamete // Ok to go down the chain, but error to try to climb back up (new Chain(new A)).then(a => new B).then(b => new C).then(c => new B).then(b => new A); - ~~~~~~~~~~ -!!! error TS2345: Argument of type '(c: C) => B' is not assignable to parameter of type '(x: C) => C'. -!!! error TS2345: Type 'B' is not assignable to type 'C'. -!!! error TS2345: Property 'z' is missing in type 'B'. \ No newline at end of file + ~~~~~ +!!! error TS2322: Type 'B' is not assignable to type 'C'. +!!! error TS2322: Property 'z' is missing in type 'B'. +!!! related TS6502 tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.ts:3:27: The expected type comes from the return type of this signature. \ No newline at end of file diff --git a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js index 8b272b582a4..69ecf8cd52d 100644 --- a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js +++ b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js @@ -26,7 +26,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.errors.txt b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.errors.txt index 56f4cad5a47..6f03e711886 100644 --- a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.errors.txt +++ b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.errors.txt @@ -1,7 +1,5 @@ -tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(7,43): error TS2345: Argument of type '(ss: S) => T' is not assignable to parameter of type '(x: S) => S'. - Type 'T' is not assignable to type 'S'. -tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(10,29): error TS2345: Argument of type '(ss: S) => T' is not assignable to parameter of type '(x: S) => S'. - Type 'T' is not assignable to type 'S'. +tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(7,49): error TS2322: Type 'T' is not assignable to type 'S'. +tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(10,35): error TS2322: Type 'T' is not assignable to type 'S'. tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(32,9): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(36,9): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(37,9): error TS2322: Type '""' is not assignable to type 'number'. @@ -15,15 +13,15 @@ tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParamete var s: S; // Ok to go down the chain, but error to climb up the chain (new Chain(t)).then(tt => s).then(ss => t); - ~~~~~~~ -!!! error TS2345: Argument of type '(ss: S) => T' is not assignable to parameter of type '(x: S) => S'. -!!! error TS2345: Type 'T' is not assignable to type 'S'. + ~ +!!! error TS2322: Type 'T' is not assignable to type 'S'. +!!! related TS6502 tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts:3:27: The expected type comes from the return type of this signature. // But error to try to climb up the chain (new Chain(s)).then(ss => t); - ~~~~~~~ -!!! error TS2345: Argument of type '(ss: S) => T' is not assignable to parameter of type '(x: S) => S'. -!!! error TS2345: Type 'T' is not assignable to type 'S'. + ~ +!!! error TS2322: Type 'T' is not assignable to type 'S'. +!!! related TS6502 tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts:3:27: The expected type comes from the return type of this signature. // Staying at T or S should be fine (new Chain(t)).then(tt => t).then(tt => t).then(tt => t); diff --git a/tests/baselines/reference/checkForObjectTooStrict.js b/tests/baselines/reference/checkForObjectTooStrict.js index d8a30eac762..d03127eaa7d 100644 --- a/tests/baselines/reference/checkForObjectTooStrict.js +++ b/tests/baselines/reference/checkForObjectTooStrict.js @@ -38,7 +38,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/checkJsxChildrenCanBeTupleType.errors.txt b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.errors.txt new file mode 100644 index 00000000000..66078776c5f --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.errors.txt @@ -0,0 +1,35 @@ +tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx(17,18): error TS2322: Type '{ children: [Element, Element, Element]; }' is not assignable to type 'Readonly'. + Types of property 'children' are incompatible. + Type '[Element, Element, Element]' is not assignable to type '[ReactNode, ReactNode]'. + Types of property 'length' are incompatible. + Type '3' is not assignable to type '2'. + + +==== tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx (1 errors) ==== + /// + + import React from 'react' + + interface ResizablePanelProps { + children: [React.ReactNode, React.ReactNode] + } + + class ResizablePanel extends React.Component< + ResizablePanelProps, any> {} + + const test = +
+
+ + + const testErr = + ~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ children: [Element, Element, Element]; }' is not assignable to type 'Readonly'. +!!! error TS2322: Types of property 'children' are incompatible. +!!! error TS2322: Type '[Element, Element, Element]' is not assignable to type '[ReactNode, ReactNode]'. +!!! error TS2322: Types of property 'length' are incompatible. +!!! error TS2322: Type '3' is not assignable to type '2'. +
+
+
+ \ No newline at end of file diff --git a/tests/baselines/reference/checkJsxChildrenCanBeTupleType.js b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.js new file mode 100644 index 00000000000..30e59613eb9 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.js @@ -0,0 +1,58 @@ +//// [checkJsxChildrenCanBeTupleType.tsx] +/// + +import React from 'react' + +interface ResizablePanelProps { + children: [React.ReactNode, React.ReactNode] +} + +class ResizablePanel extends React.Component< + ResizablePanelProps, any> {} + +const test = +
+
+ + +const testErr = +
+
+
+ + +//// [checkJsxChildrenCanBeTupleType.js] +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +exports.__esModule = true; +var react_1 = __importDefault(require("react")); +var ResizablePanel = /** @class */ (function (_super) { + __extends(ResizablePanel, _super); + function ResizablePanel() { + return _super !== null && _super.apply(this, arguments) || this; + } + return ResizablePanel; +}(react_1["default"].Component)); +var test = react_1["default"].createElement(ResizablePanel, null, + react_1["default"].createElement("div", null), + react_1["default"].createElement("div", null)); +var testErr = react_1["default"].createElement(ResizablePanel, null, + react_1["default"].createElement("div", null), + react_1["default"].createElement("div", null), + react_1["default"].createElement("div", null)); diff --git a/tests/baselines/reference/checkJsxChildrenCanBeTupleType.symbols b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.symbols new file mode 100644 index 00000000000..05c7042ad10 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.symbols @@ -0,0 +1,55 @@ +=== tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx === +/// + +import React from 'react' +>React : Symbol(React, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 6)) + +interface ResizablePanelProps { +>ResizablePanelProps : Symbol(ResizablePanelProps, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 25)) + + children: [React.ReactNode, React.ReactNode] +>children : Symbol(ResizablePanelProps.children, Decl(checkJsxChildrenCanBeTupleType.tsx, 4, 31)) +>React : Symbol(React, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 6)) +>ReactNode : Symbol(React.ReactNode, Decl(react16.d.ts, 216, 49)) +>React : Symbol(React, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 6)) +>ReactNode : Symbol(React.ReactNode, Decl(react16.d.ts, 216, 49)) +} + +class ResizablePanel extends React.Component< +>ResizablePanel : Symbol(ResizablePanel, Decl(checkJsxChildrenCanBeTupleType.tsx, 6, 1)) +>React.Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>React : Symbol(React, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 6)) +>Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) + + ResizablePanelProps, any> {} +>ResizablePanelProps : Symbol(ResizablePanelProps, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 25)) + +const test = +>test : Symbol(test, Decl(checkJsxChildrenCanBeTupleType.tsx, 11, 5)) +>ResizablePanel : Symbol(ResizablePanel, Decl(checkJsxChildrenCanBeTupleType.tsx, 6, 1)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + + +>ResizablePanel : Symbol(ResizablePanel, Decl(checkJsxChildrenCanBeTupleType.tsx, 6, 1)) + +const testErr = +>testErr : Symbol(testErr, Decl(checkJsxChildrenCanBeTupleType.tsx, 16, 5)) +>ResizablePanel : Symbol(ResizablePanel, Decl(checkJsxChildrenCanBeTupleType.tsx, 6, 1)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + + +>ResizablePanel : Symbol(ResizablePanel, Decl(checkJsxChildrenCanBeTupleType.tsx, 6, 1)) + diff --git a/tests/baselines/reference/checkJsxChildrenCanBeTupleType.types b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.types new file mode 100644 index 00000000000..a710c9b1787 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.types @@ -0,0 +1,57 @@ +=== tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx === +/// + +import React from 'react' +>React : typeof React + +interface ResizablePanelProps { + children: [React.ReactNode, React.ReactNode] +>children : [React.ReactNode, React.ReactNode] +>React : any +>React : any +} + +class ResizablePanel extends React.Component< +>ResizablePanel : ResizablePanel +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component + + ResizablePanelProps, any> {} + +const test = +>test : JSX.Element +>
: JSX.Element +>ResizablePanel : typeof ResizablePanel + +
+>
: JSX.Element +>div : any + +
+>
: JSX.Element +>div : any + + +>ResizablePanel : typeof ResizablePanel + +const testErr = +>testErr : JSX.Element +>
: JSX.Element +>ResizablePanel : typeof ResizablePanel + +
+>
: JSX.Element +>div : any + +
+>
: JSX.Element +>div : any + +
+>
: JSX.Element +>div : any + + +>ResizablePanel : typeof ResizablePanel + diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.js b/tests/baselines/reference/checkJsxChildrenProperty12.js index 5b1d1d1b794..44fe4e1053d 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty12.js +++ b/tests/baselines/reference/checkJsxChildrenProperty12.js @@ -40,7 +40,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/checkJsxChildrenProperty13.js b/tests/baselines/reference/checkJsxChildrenProperty13.js index 45ef75b88b1..dcdf7ac1e88 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty13.js +++ b/tests/baselines/reference/checkJsxChildrenProperty13.js @@ -35,7 +35,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt index cf999188ebc..6878372be8b 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt @@ -1,7 +1,8 @@ -tests/cases/conformance/jsx/file.tsx(42,11): error TS2322: Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'SingleChildProp'. - Types of property 'children' are incompatible. - Type 'Element[]' is not assignable to type 'Element'. - Property 'type' is missing in type 'Element[]'. +tests/cases/conformance/jsx/file.tsx(42,11): error TS2322: Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'IntrinsicAttributes & SingleChildProp'. + Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'SingleChildProp'. + Types of property 'children' are incompatible. + Type 'Element[]' is not assignable to type 'Element'. + Property 'type' is missing in type 'Element[]'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -48,7 +49,8 @@ tests/cases/conformance/jsx/file.tsx(42,11): error TS2322: Type '{ children: Ele // Error let k5 = <>}/> + + // Component Class as Props + class MyButtonComponent extends React.Component<{},{}> { + } + + + + \ No newline at end of file diff --git a/tests/baselines/reference/tsxUnionTypeComponent1.js b/tests/baselines/reference/tsxUnionTypeComponent1.js index 360a408d3f9..9e004413575 100644 --- a/tests/baselines/reference/tsxUnionTypeComponent1.js +++ b/tests/baselines/reference/tsxUnionTypeComponent1.js @@ -31,7 +31,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/tupleLengthCheck.errors.txt b/tests/baselines/reference/tupleLengthCheck.errors.txt index f90adbf3525..1c6fe909135 100644 --- a/tests/baselines/reference/tupleLengthCheck.errors.txt +++ b/tests/baselines/reference/tupleLengthCheck.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/tuple/tupleLengthCheck.ts(5,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/tuple/tupleLengthCheck.ts(6,14): error TS2733: Index '1000' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/tuple/tupleLengthCheck.ts(5,14): error TS2339: Property '2' does not exist on type '[number, string]'. +tests/cases/conformance/types/tuple/tupleLengthCheck.ts(6,14): error TS2339: Property '1000' does not exist on type '[number, string]'. ==== tests/cases/conformance/types/tuple/tupleLengthCheck.ts (2 errors) ==== @@ -9,10 +9,10 @@ tests/cases/conformance/types/tuple/tupleLengthCheck.ts(6,14): error TS2733: Ind const a1 = a[1] const a2 = a[2] ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, string]'. const a3 = a[1000] ~~~~ -!!! error TS2733: Index '1000' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '1000' does not exist on type '[number, string]'. const a4 = rest[1] const a5 = rest[2] diff --git a/tests/baselines/reference/tupleLengthCheck.types b/tests/baselines/reference/tupleLengthCheck.types index be4372c669c..67ccb006a81 100644 --- a/tests/baselines/reference/tupleLengthCheck.types +++ b/tests/baselines/reference/tupleLengthCheck.types @@ -12,14 +12,14 @@ const a1 = a[1] >1 : 1 const a2 = a[2] ->a2 : string | number ->a[2] : string | number +>a2 : undefined +>a[2] : undefined >a : [number, string] >2 : 2 const a3 = a[1000] ->a3 : string | number ->a[1000] : string | number +>a3 : undefined +>a[1000] : undefined >a : [number, string] >1000 : 1000 diff --git a/tests/baselines/reference/tupleTypes.errors.txt b/tests/baselines/reference/tupleTypes.errors.txt index 4543eb202da..95daf5ce0ef 100644 --- a/tests/baselines/reference/tupleTypes.errors.txt +++ b/tests/baselines/reference/tupleTypes.errors.txt @@ -1,4 +1,5 @@ -tests/cases/compiler/tupleTypes.ts(11,12): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/compiler/tupleTypes.ts(11,12): error TS2339: Property '2' does not exist on type '[number, string]'. +tests/cases/compiler/tupleTypes.ts(12,5): error TS2403: Subsequent variable declarations must have the same type. Variable 't2' must be of type 'undefined', but here has type 'string | number'. tests/cases/compiler/tupleTypes.ts(14,1): error TS2322: Type '[]' is not assignable to type '[number, string]'. Property '0' is missing in type '[]'. tests/cases/compiler/tupleTypes.ts(15,1): error TS2322: Type '[number]' is not assignable to type '[number, string]'. @@ -8,7 +9,8 @@ tests/cases/compiler/tupleTypes.ts(17,15): error TS2322: Type 'number' is not as tests/cases/compiler/tupleTypes.ts(18,1): error TS2322: Type '[number, string, number]' is not assignable to type '[number, string]'. Types of property 'length' are incompatible. Type '3' is not assignable to type '2'. -tests/cases/compiler/tupleTypes.ts(35,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/compiler/tupleTypes.ts(35,14): error TS2339: Property '2' does not exist on type '[number, string]'. +tests/cases/compiler/tupleTypes.ts(36,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'tt2' must be of type 'undefined', but here has type 'string | number'. tests/cases/compiler/tupleTypes.ts(41,1): error TS2322: Type '[]' is not assignable to type '[number, string]'. tests/cases/compiler/tupleTypes.ts(47,1): error TS2322: Type '[number, string]' is not assignable to type 'number[]'. Type 'string | number' is not assignable to type 'number'. @@ -22,7 +24,7 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n Type '{}' is not assignable to type 'string'. -==== tests/cases/compiler/tupleTypes.ts (12 errors) ==== +==== tests/cases/compiler/tupleTypes.ts (14 errors) ==== var v1: []; // Error var v2: [number]; var v3: [number, string]; @@ -35,8 +37,10 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n var t1: string; var t2 = t[2]; // number|string ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, string]'. var t2: number|string; + ~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 't2' must be of type 'undefined', but here has type 'string | number'. t = []; // Error ~ @@ -75,8 +79,10 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n var tt1: string; var tt2 = tt[2]; ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, string]'. var tt2: number | string; + ~~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'tt2' must be of type 'undefined', but here has type 'string | number'. tt = tuple2(1, undefined); tt = [1, undefined]; diff --git a/tests/baselines/reference/tupleTypes.types b/tests/baselines/reference/tupleTypes.types index 45fec41112c..12eaf588b98 100644 --- a/tests/baselines/reference/tupleTypes.types +++ b/tests/baselines/reference/tupleTypes.types @@ -33,13 +33,13 @@ var t1: string; >t1 : string var t2 = t[2]; // number|string ->t2 : string | number ->t[2] : string | number +>t2 : undefined +>t[2] : undefined >t : [number, string] >2 : 2 var t2: number|string; ->t2 : string | number +>t2 : undefined t = []; // Error >t = [] : [] @@ -144,13 +144,13 @@ var tt1: string; >tt1 : string var tt2 = tt[2]; ->tt2 : string | number ->tt[2] : string | number +>tt2 : undefined +>tt[2] : undefined >tt : [number, string] >2 : 2 var tt2: number | string; ->tt2 : string | number +>tt2 : undefined tt = tuple2(1, undefined); >tt = tuple2(1, undefined) : [number, any] diff --git a/tests/baselines/reference/typeAliasFunctionTypeSharedSymbol.js b/tests/baselines/reference/typeAliasFunctionTypeSharedSymbol.js index dcec415ee79..1eedb2413ea 100644 --- a/tests/baselines/reference/typeAliasFunctionTypeSharedSymbol.js +++ b/tests/baselines/reference/typeAliasFunctionTypeSharedSymbol.js @@ -21,7 +21,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeArgumentInferenceWithConstraints.errors.txt b/tests/baselines/reference/typeArgumentInferenceWithConstraints.errors.txt index 9888c8558f1..3b7750f23f0 100644 --- a/tests/baselines/reference/typeArgumentInferenceWithConstraints.errors.txt +++ b/tests/baselines/reference/typeArgumentInferenceWithConstraints.errors.txt @@ -1,8 +1,7 @@ tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithConstraints.ts(11,17): error TS2344: Type '{}' does not satisfy the constraint 'number'. tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithConstraints.ts(16,23): error TS2344: Type 'number' does not satisfy the constraint 'string'. tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithConstraints.ts(17,23): error TS2344: Type '{}' does not satisfy the constraint 'number'. -tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithConstraints.ts(33,15): error TS2345: Argument of type '() => string' is not assignable to parameter of type '() => Window'. - Type 'string' is not assignable to type 'Window'. +tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithConstraints.ts(33,21): error TS2322: Type 'string' is not assignable to type 'Window'. tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithConstraints.ts(35,15): error TS2344: Type 'number' does not satisfy the constraint 'Window'. tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithConstraints.ts(41,35): error TS2345: Argument of type '(x: string) => string' is not assignable to parameter of type '(x: number) => void'. Types of parameters 'x' and 'x' are incompatible. @@ -61,9 +60,9 @@ tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithConst // Generic call with argument of function type whose parameter is not of type parameter type but body/return type uses type parameter function someGenerics3(producer: () => T) { } someGenerics3(() => ''); // Error - ~~~~~~~~ -!!! error TS2345: Argument of type '() => string' is not assignable to parameter of type '() => Window'. -!!! error TS2345: Type 'string' is not assignable to type 'Window'. + ~~ +!!! error TS2322: Type 'string' is not assignable to type 'Window'. +!!! related TS6502 tests/cases/conformance/expressions/functionCalls/typeArgumentInferenceWithConstraints.ts:32:52: The expected type comes from the return type of this signature. someGenerics3(() => undefined); someGenerics3(() => 3); // Error ~~~~~~ diff --git a/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt b/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt index 0df5d91865d..551b863c604 100644 --- a/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt +++ b/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt @@ -12,4 +12,5 @@ tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2554: E !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. x.b(); // error ~~~~~~~~~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/typeAssertionToGenericFunctionType.ts:3:12: An argument for 'x' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/typeAssertions.js b/tests/baselines/reference/typeAssertions.js index 04fa6d479a6..8f37011a273 100644 --- a/tests/baselines/reference/typeAssertions.js +++ b/tests/baselines/reference/typeAssertions.js @@ -58,7 +58,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeFromPropertyAssignment12.types b/tests/baselines/reference/typeFromPropertyAssignment12.types index 21b8dd7e32c..c2bee51375b 100644 --- a/tests/baselines/reference/typeFromPropertyAssignment12.types +++ b/tests/baselines/reference/typeFromPropertyAssignment12.types @@ -1,7 +1,7 @@ === tests/cases/conformance/salsa/module.js === var Outer = function(element, config) {}; ->Outer : { (element: any, config: any): void; Pos(line: any, ch: any): void; } ->function(element, config) {} : { (element: any, config: any): void; Pos(line: any, ch: any): void; } +>Outer : { (element: any, config: any): void; Pos(line: any, ch: any): Pos; } +>function(element, config) {} : { (element: any, config: any): void; Pos(line: any, ch: any): Pos; } >element : any >config : any @@ -10,7 +10,7 @@ var Outer = function(element, config) {}; Outer.Pos = function (line, ch) {}; >Outer.Pos = function (line, ch) {} : typeof Pos >Outer.Pos : typeof Pos ->Outer : { (element: any, config: any): void; Pos(line: any, ch: any): void; } +>Outer : { (element: any, config: any): void; Pos(line: any, ch: any): Pos; } >Pos : typeof Pos >function (line, ch) {} : typeof Pos >line : any @@ -21,7 +21,7 @@ Outer.Pos.prototype.line; >Outer.Pos.prototype.line : any >Outer.Pos.prototype : any >Outer.Pos : typeof Pos ->Outer : { (element: any, config: any): void; Pos(line: any, ch: any): void; } +>Outer : { (element: any, config: any): void; Pos(line: any, ch: any): Pos; } >Pos : typeof Pos >prototype : any >line : any @@ -30,7 +30,7 @@ var pos = new Outer.Pos(1, 'x'); >pos : Pos >new Outer.Pos(1, 'x') : Pos >Outer.Pos : typeof Pos ->Outer : { (element: any, config: any): void; Pos(line: any, ch: any): void; } +>Outer : { (element: any, config: any): void; Pos(line: any, ch: any): Pos; } >Pos : typeof Pos >1 : 1 >'x' : "x" diff --git a/tests/baselines/reference/typeFromPropertyAssignment35.symbols b/tests/baselines/reference/typeFromPropertyAssignment35.symbols new file mode 100644 index 00000000000..d651748d1cc --- /dev/null +++ b/tests/baselines/reference/typeFromPropertyAssignment35.symbols @@ -0,0 +1,51 @@ +=== tests/cases/conformance/salsa/bug26877.js === +/** @param {Emu.D} x */ +function ollKorrect(x) { +>ollKorrect : Symbol(ollKorrect, Decl(bug26877.js, 0, 0)) +>x : Symbol(x, Decl(bug26877.js, 1, 20)) + + x._model +>x._model : Symbol(D._model, Decl(bug26877.js, 7, 19)) +>x : Symbol(x, Decl(bug26877.js, 1, 20)) +>_model : Symbol(D._model, Decl(bug26877.js, 7, 19)) + + const y = new Emu.D() +>y : Symbol(y, Decl(bug26877.js, 3, 9)) +>Emu.D : Symbol(Emu.D, Decl(bug26877.js, 5, 1), Decl(second.js, 2, 4)) +>Emu : Symbol(Emu, Decl(bug26877.js, 5, 1), Decl(second.js, 0, 3), Decl(second.js, 0, 12)) +>D : Symbol(Emu.D, Decl(bug26877.js, 5, 1), Decl(second.js, 2, 4)) + + const z = Emu.D._wrapperInstance; +>z : Symbol(z, Decl(bug26877.js, 4, 9)) +>Emu.D._wrapperInstance : Symbol(Emu.D._wrapperInstance, Decl(second.js, 0, 12)) +>Emu.D : Symbol(Emu.D, Decl(bug26877.js, 5, 1), Decl(second.js, 2, 4)) +>Emu : Symbol(Emu, Decl(bug26877.js, 5, 1), Decl(second.js, 0, 3), Decl(second.js, 0, 12)) +>D : Symbol(Emu.D, Decl(bug26877.js, 5, 1), Decl(second.js, 2, 4)) +>_wrapperInstance : Symbol(Emu.D._wrapperInstance, Decl(second.js, 0, 12)) +} +Emu.D = class { +>Emu.D : Symbol(Emu.D, Decl(bug26877.js, 5, 1), Decl(second.js, 2, 4)) +>Emu : Symbol(Emu, Decl(bug26877.js, 5, 1), Decl(second.js, 0, 3), Decl(second.js, 0, 12)) +>D : Symbol(Emu.D, Decl(bug26877.js, 5, 1), Decl(second.js, 2, 4)) + + constructor() { + this._model = 1 +>this._model : Symbol(D._model, Decl(bug26877.js, 7, 19)) +>this : Symbol(D, Decl(bug26877.js, 6, 7)) +>_model : Symbol(D._model, Decl(bug26877.js, 7, 19)) + } +} + +=== tests/cases/conformance/salsa/second.js === +var Emu = {} +>Emu : Symbol(Emu, Decl(bug26877.js, 5, 1), Decl(second.js, 0, 3), Decl(second.js, 0, 12)) + +/** @type {string} */ +Emu.D._wrapperInstance; +>Emu.D._wrapperInstance : Symbol(Emu.D._wrapperInstance, Decl(second.js, 0, 12)) +>Emu.D : Symbol(Emu.D, Decl(bug26877.js, 5, 1), Decl(second.js, 2, 4)) +>Emu : Symbol(Emu, Decl(bug26877.js, 5, 1), Decl(second.js, 0, 3), Decl(second.js, 0, 12)) +>D : Symbol(Emu.D, Decl(bug26877.js, 5, 1), Decl(second.js, 2, 4)) +>_wrapperInstance : Symbol(Emu.D._wrapperInstance, Decl(second.js, 0, 12)) + + diff --git a/tests/baselines/reference/typeFromPropertyAssignment35.types b/tests/baselines/reference/typeFromPropertyAssignment35.types new file mode 100644 index 00000000000..678adb1ba53 --- /dev/null +++ b/tests/baselines/reference/typeFromPropertyAssignment35.types @@ -0,0 +1,57 @@ +=== tests/cases/conformance/salsa/bug26877.js === +/** @param {Emu.D} x */ +function ollKorrect(x) { +>ollKorrect : (x: D) => void +>x : D + + x._model +>x._model : number +>x : D +>_model : number + + const y = new Emu.D() +>y : D +>new Emu.D() : D +>Emu.D : typeof D +>Emu : typeof Emu +>D : typeof D + + const z = Emu.D._wrapperInstance; +>z : string +>Emu.D._wrapperInstance : string +>Emu.D : typeof D +>Emu : typeof Emu +>D : typeof D +>_wrapperInstance : string +} +Emu.D = class { +>Emu.D = class { constructor() { this._model = 1 }} : typeof D +>Emu.D : typeof D +>Emu : typeof Emu +>D : typeof D +>class { constructor() { this._model = 1 }} : typeof D + + constructor() { + this._model = 1 +>this._model = 1 : 1 +>this._model : number +>this : this +>_model : number +>1 : 1 + } +} + +=== tests/cases/conformance/salsa/second.js === +var Emu = {} +>Emu : typeof Emu +>{} : {} + +/** @type {string} */ +Emu.D._wrapperInstance; +>Emu.D._wrapperInstance : string +>Emu.D : typeof D +>Emu : typeof Emu +>D : typeof D +>_wrapperInstance : string + + diff --git a/tests/baselines/reference/typeFromPropertyAssignment36.errors.txt b/tests/baselines/reference/typeFromPropertyAssignment36.errors.txt new file mode 100644 index 00000000000..3cd98f56b4b --- /dev/null +++ b/tests/baselines/reference/typeFromPropertyAssignment36.errors.txt @@ -0,0 +1,85 @@ +tests/cases/conformance/salsa/typeFromPropertyAssignment36.ts(11,7): error TS2565: Property 'q' is used before being assigned. +tests/cases/conformance/salsa/typeFromPropertyAssignment36.ts(42,3): error TS2565: Property 'q' is used before being assigned. +tests/cases/conformance/salsa/typeFromPropertyAssignment36.ts(64,3): error TS2565: Property 'expando' is used before being assigned. + + +==== tests/cases/conformance/salsa/typeFromPropertyAssignment36.ts (3 errors) ==== + function f(b: boolean) { + function d() { + } + d.e = 12 + d.e + + if (b) { + d.q = false + } + // error d.q might not be assigned + d.q + ~ +!!! error TS2565: Property 'q' is used before being assigned. + if (b) { + d.q = false + } + else { + d.q = true + } + d.q + if (b) { + d.r = 1 + } + else { + d.r = 2 + } + d.r + if (b) { + d.s = 'hi' + } + return d + } + // OK to access possibly-unassigned properties outside the initialising scope + var test = f(true).s + + function d() { + } + d.e = 12 + d.e + + if (!!false) { + d.q = false + } + d.q + ~ +!!! error TS2565: Property 'q' is used before being assigned. + if (!!false) { + d.q = false + } + else { + d.q = true + } + d.q + if (!!false) { + d.r = 1 + } + else { + d.r = 2 + } + d.r + + // test function expressions too + const g = function() { + } + if (!!false) { + g.expando = 1 + } + g.expando // error + ~~~~~~~ +!!! error TS2565: Property 'expando' is used before being assigned. + + if (!!false) { + g.both = 'hi' + } + else { + g.both = 0 + } + g.both + \ No newline at end of file diff --git a/tests/baselines/reference/typeFromPropertyAssignment36.js b/tests/baselines/reference/typeFromPropertyAssignment36.js new file mode 100644 index 00000000000..ae0c2ec244b --- /dev/null +++ b/tests/baselines/reference/typeFromPropertyAssignment36.js @@ -0,0 +1,144 @@ +//// [typeFromPropertyAssignment36.ts] +function f(b: boolean) { + function d() { + } + d.e = 12 + d.e + + if (b) { + d.q = false + } + // error d.q might not be assigned + d.q + if (b) { + d.q = false + } + else { + d.q = true + } + d.q + if (b) { + d.r = 1 + } + else { + d.r = 2 + } + d.r + if (b) { + d.s = 'hi' + } + return d +} +// OK to access possibly-unassigned properties outside the initialising scope +var test = f(true).s + +function d() { +} +d.e = 12 +d.e + +if (!!false) { + d.q = false +} +d.q +if (!!false) { + d.q = false +} +else { + d.q = true +} +d.q +if (!!false) { + d.r = 1 +} +else { + d.r = 2 +} +d.r + +// test function expressions too +const g = function() { +} +if (!!false) { + g.expando = 1 +} +g.expando // error + +if (!!false) { + g.both = 'hi' +} +else { + g.both = 0 +} +g.both + + +//// [typeFromPropertyAssignment36.js] +"use strict"; +function f(b) { + function d() { + } + d.e = 12; + d.e; + if (b) { + d.q = false; + } + // error d.q might not be assigned + d.q; + if (b) { + d.q = false; + } + else { + d.q = true; + } + d.q; + if (b) { + d.r = 1; + } + else { + d.r = 2; + } + d.r; + if (b) { + d.s = 'hi'; + } + return d; +} +// OK to access possibly-unassigned properties outside the initialising scope +var test = f(true).s; +function d() { +} +d.e = 12; +d.e; +if (!!false) { + d.q = false; +} +d.q; +if (!!false) { + d.q = false; +} +else { + d.q = true; +} +d.q; +if (!!false) { + d.r = 1; +} +else { + d.r = 2; +} +d.r; +// test function expressions too +var g = function () { +}; +if (!!false) { + g.expando = 1; +} +g.expando; // error +if (!!false) { + g.both = 'hi'; +} +else { + g.both = 0; +} +g.both; diff --git a/tests/baselines/reference/typeFromPropertyAssignment36.symbols b/tests/baselines/reference/typeFromPropertyAssignment36.symbols new file mode 100644 index 00000000000..1c90cf5684c --- /dev/null +++ b/tests/baselines/reference/typeFromPropertyAssignment36.symbols @@ -0,0 +1,178 @@ +=== tests/cases/conformance/salsa/typeFromPropertyAssignment36.ts === +function f(b: boolean) { +>f : Symbol(f, Decl(typeFromPropertyAssignment36.ts, 0, 0)) +>b : Symbol(b, Decl(typeFromPropertyAssignment36.ts, 0, 11)) + + function d() { +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) + } + d.e = 12 +>d.e : Symbol(d.e, Decl(typeFromPropertyAssignment36.ts, 2, 5)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>e : Symbol(d.e, Decl(typeFromPropertyAssignment36.ts, 2, 5)) + + d.e +>d.e : Symbol(d.e, Decl(typeFromPropertyAssignment36.ts, 2, 5)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>e : Symbol(d.e, Decl(typeFromPropertyAssignment36.ts, 2, 5)) + + if (b) { +>b : Symbol(b, Decl(typeFromPropertyAssignment36.ts, 0, 11)) + + d.q = false +>d.q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 6, 12), Decl(typeFromPropertyAssignment36.ts, 11, 12), Decl(typeFromPropertyAssignment36.ts, 14, 10)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 6, 12), Decl(typeFromPropertyAssignment36.ts, 11, 12), Decl(typeFromPropertyAssignment36.ts, 14, 10)) + } + // error d.q might not be assigned + d.q +>d.q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 6, 12), Decl(typeFromPropertyAssignment36.ts, 11, 12), Decl(typeFromPropertyAssignment36.ts, 14, 10)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 6, 12), Decl(typeFromPropertyAssignment36.ts, 11, 12), Decl(typeFromPropertyAssignment36.ts, 14, 10)) + + if (b) { +>b : Symbol(b, Decl(typeFromPropertyAssignment36.ts, 0, 11)) + + d.q = false +>d.q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 6, 12), Decl(typeFromPropertyAssignment36.ts, 11, 12), Decl(typeFromPropertyAssignment36.ts, 14, 10)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 6, 12), Decl(typeFromPropertyAssignment36.ts, 11, 12), Decl(typeFromPropertyAssignment36.ts, 14, 10)) + } + else { + d.q = true +>d.q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 6, 12), Decl(typeFromPropertyAssignment36.ts, 11, 12), Decl(typeFromPropertyAssignment36.ts, 14, 10)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 6, 12), Decl(typeFromPropertyAssignment36.ts, 11, 12), Decl(typeFromPropertyAssignment36.ts, 14, 10)) + } + d.q +>d.q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 6, 12), Decl(typeFromPropertyAssignment36.ts, 11, 12), Decl(typeFromPropertyAssignment36.ts, 14, 10)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 6, 12), Decl(typeFromPropertyAssignment36.ts, 11, 12), Decl(typeFromPropertyAssignment36.ts, 14, 10)) + + if (b) { +>b : Symbol(b, Decl(typeFromPropertyAssignment36.ts, 0, 11)) + + d.r = 1 +>d.r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 18, 12), Decl(typeFromPropertyAssignment36.ts, 21, 10)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 18, 12), Decl(typeFromPropertyAssignment36.ts, 21, 10)) + } + else { + d.r = 2 +>d.r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 18, 12), Decl(typeFromPropertyAssignment36.ts, 21, 10)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 18, 12), Decl(typeFromPropertyAssignment36.ts, 21, 10)) + } + d.r +>d.r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 18, 12), Decl(typeFromPropertyAssignment36.ts, 21, 10)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 18, 12), Decl(typeFromPropertyAssignment36.ts, 21, 10)) + + if (b) { +>b : Symbol(b, Decl(typeFromPropertyAssignment36.ts, 0, 11)) + + d.s = 'hi' +>d.s : Symbol(d.s, Decl(typeFromPropertyAssignment36.ts, 25, 12)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +>s : Symbol(d.s, Decl(typeFromPropertyAssignment36.ts, 25, 12)) + } + return d +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 0, 24)) +} +// OK to access possibly-unassigned properties outside the initialising scope +var test = f(true).s +>test : Symbol(test, Decl(typeFromPropertyAssignment36.ts, 31, 3)) +>f(true).s : Symbol(d.s, Decl(typeFromPropertyAssignment36.ts, 25, 12)) +>f : Symbol(f, Decl(typeFromPropertyAssignment36.ts, 0, 0)) +>s : Symbol(d.s, Decl(typeFromPropertyAssignment36.ts, 25, 12)) + +function d() { +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +} +d.e = 12 +>d.e : Symbol(d.e, Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>e : Symbol(d.e, Decl(typeFromPropertyAssignment36.ts, 34, 1)) + +d.e +>d.e : Symbol(d.e, Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>e : Symbol(d.e, Decl(typeFromPropertyAssignment36.ts, 34, 1)) + +if (!!false) { + d.q = false +>d.q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 38, 14), Decl(typeFromPropertyAssignment36.ts, 42, 14), Decl(typeFromPropertyAssignment36.ts, 45, 6)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 38, 14), Decl(typeFromPropertyAssignment36.ts, 42, 14), Decl(typeFromPropertyAssignment36.ts, 45, 6)) +} +d.q +>d.q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 38, 14), Decl(typeFromPropertyAssignment36.ts, 42, 14), Decl(typeFromPropertyAssignment36.ts, 45, 6)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 38, 14), Decl(typeFromPropertyAssignment36.ts, 42, 14), Decl(typeFromPropertyAssignment36.ts, 45, 6)) + +if (!!false) { + d.q = false +>d.q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 38, 14), Decl(typeFromPropertyAssignment36.ts, 42, 14), Decl(typeFromPropertyAssignment36.ts, 45, 6)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 38, 14), Decl(typeFromPropertyAssignment36.ts, 42, 14), Decl(typeFromPropertyAssignment36.ts, 45, 6)) +} +else { + d.q = true +>d.q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 38, 14), Decl(typeFromPropertyAssignment36.ts, 42, 14), Decl(typeFromPropertyAssignment36.ts, 45, 6)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 38, 14), Decl(typeFromPropertyAssignment36.ts, 42, 14), Decl(typeFromPropertyAssignment36.ts, 45, 6)) +} +d.q +>d.q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 38, 14), Decl(typeFromPropertyAssignment36.ts, 42, 14), Decl(typeFromPropertyAssignment36.ts, 45, 6)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>q : Symbol(d.q, Decl(typeFromPropertyAssignment36.ts, 38, 14), Decl(typeFromPropertyAssignment36.ts, 42, 14), Decl(typeFromPropertyAssignment36.ts, 45, 6)) + +if (!!false) { + d.r = 1 +>d.r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 49, 14), Decl(typeFromPropertyAssignment36.ts, 52, 6)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 49, 14), Decl(typeFromPropertyAssignment36.ts, 52, 6)) +} +else { + d.r = 2 +>d.r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 49, 14), Decl(typeFromPropertyAssignment36.ts, 52, 6)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 49, 14), Decl(typeFromPropertyAssignment36.ts, 52, 6)) +} +d.r +>d.r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 49, 14), Decl(typeFromPropertyAssignment36.ts, 52, 6)) +>d : Symbol(d, Decl(typeFromPropertyAssignment36.ts, 31, 20), Decl(typeFromPropertyAssignment36.ts, 34, 1)) +>r : Symbol(d.r, Decl(typeFromPropertyAssignment36.ts, 49, 14), Decl(typeFromPropertyAssignment36.ts, 52, 6)) + +// test function expressions too +const g = function() { +>g : Symbol(g, Decl(typeFromPropertyAssignment36.ts, 58, 5)) +} +if (!!false) { + g.expando = 1 +>g.expando : Symbol(g.expando, Decl(typeFromPropertyAssignment36.ts, 60, 14)) +>g : Symbol(g, Decl(typeFromPropertyAssignment36.ts, 58, 5)) +>expando : Symbol(g.expando, Decl(typeFromPropertyAssignment36.ts, 60, 14)) +} +g.expando // error +>g.expando : Symbol(g.expando, Decl(typeFromPropertyAssignment36.ts, 60, 14)) +>g : Symbol(g, Decl(typeFromPropertyAssignment36.ts, 58, 5)) +>expando : Symbol(g.expando, Decl(typeFromPropertyAssignment36.ts, 60, 14)) + +if (!!false) { + g.both = 'hi' +>g.both : Symbol(g.both, Decl(typeFromPropertyAssignment36.ts, 65, 14), Decl(typeFromPropertyAssignment36.ts, 68, 6)) +>g : Symbol(g, Decl(typeFromPropertyAssignment36.ts, 58, 5)) +>both : Symbol(g.both, Decl(typeFromPropertyAssignment36.ts, 65, 14), Decl(typeFromPropertyAssignment36.ts, 68, 6)) +} +else { + g.both = 0 +>g.both : Symbol(g.both, Decl(typeFromPropertyAssignment36.ts, 65, 14), Decl(typeFromPropertyAssignment36.ts, 68, 6)) +>g : Symbol(g, Decl(typeFromPropertyAssignment36.ts, 58, 5)) +>both : Symbol(g.both, Decl(typeFromPropertyAssignment36.ts, 65, 14), Decl(typeFromPropertyAssignment36.ts, 68, 6)) +} +g.both +>g.both : Symbol(g.both, Decl(typeFromPropertyAssignment36.ts, 65, 14), Decl(typeFromPropertyAssignment36.ts, 68, 6)) +>g : Symbol(g, Decl(typeFromPropertyAssignment36.ts, 58, 5)) +>both : Symbol(g.both, Decl(typeFromPropertyAssignment36.ts, 65, 14), Decl(typeFromPropertyAssignment36.ts, 68, 6)) + diff --git a/tests/baselines/reference/typeFromPropertyAssignment36.types b/tests/baselines/reference/typeFromPropertyAssignment36.types new file mode 100644 index 00000000000..4eb184fa0bb --- /dev/null +++ b/tests/baselines/reference/typeFromPropertyAssignment36.types @@ -0,0 +1,233 @@ +=== tests/cases/conformance/salsa/typeFromPropertyAssignment36.ts === +function f(b: boolean) { +>f : (b: boolean) => { (): void; e: number; q: boolean; r: number; s: string; } +>b : boolean + + function d() { +>d : { (): void; e: number; q: boolean; r: number; s: string; } + } + d.e = 12 +>d.e = 12 : 12 +>d.e : number +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>e : number +>12 : 12 + + d.e +>d.e : number +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>e : number + + if (b) { +>b : boolean + + d.q = false +>d.q = false : false +>d.q : boolean +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>q : boolean +>false : false + } + // error d.q might not be assigned + d.q +>d.q : boolean +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>q : boolean + + if (b) { +>b : boolean + + d.q = false +>d.q = false : false +>d.q : boolean +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>q : boolean +>false : false + } + else { + d.q = true +>d.q = true : true +>d.q : boolean +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>q : boolean +>true : true + } + d.q +>d.q : boolean +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>q : boolean + + if (b) { +>b : boolean + + d.r = 1 +>d.r = 1 : 1 +>d.r : number +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>r : number +>1 : 1 + } + else { + d.r = 2 +>d.r = 2 : 2 +>d.r : number +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>r : number +>2 : 2 + } + d.r +>d.r : number +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>r : number + + if (b) { +>b : boolean + + d.s = 'hi' +>d.s = 'hi' : "hi" +>d.s : string +>d : { (): void; e: number; q: boolean; r: number; s: string; } +>s : string +>'hi' : "hi" + } + return d +>d : { (): void; e: number; q: boolean; r: number; s: string; } +} +// OK to access possibly-unassigned properties outside the initialising scope +var test = f(true).s +>test : string +>f(true).s : string +>f(true) : { (): void; e: number; q: boolean; r: number; s: string; } +>f : (b: boolean) => { (): void; e: number; q: boolean; r: number; s: string; } +>true : true +>s : string + +function d() { +>d : typeof d +} +d.e = 12 +>d.e = 12 : 12 +>d.e : number +>d : typeof d +>e : number +>12 : 12 + +d.e +>d.e : number +>d : typeof d +>e : number + +if (!!false) { +>!!false : false +>!false : true +>false : false + + d.q = false +>d.q = false : false +>d.q : boolean +>d : typeof d +>q : boolean +>false : false +} +d.q +>d.q : boolean +>d : typeof d +>q : boolean + +if (!!false) { +>!!false : false +>!false : true +>false : false + + d.q = false +>d.q = false : false +>d.q : boolean +>d : typeof d +>q : boolean +>false : false +} +else { + d.q = true +>d.q = true : true +>d.q : boolean +>d : typeof d +>q : boolean +>true : true +} +d.q +>d.q : boolean +>d : typeof d +>q : boolean + +if (!!false) { +>!!false : false +>!false : true +>false : false + + d.r = 1 +>d.r = 1 : 1 +>d.r : number +>d : typeof d +>r : number +>1 : 1 +} +else { + d.r = 2 +>d.r = 2 : 2 +>d.r : number +>d : typeof d +>r : number +>2 : 2 +} +d.r +>d.r : number +>d : typeof d +>r : number + +// test function expressions too +const g = function() { +>g : { (): void; expando: number; both: string | number; } +>function() {} : { (): void; expando: number; both: string | number; } +} +if (!!false) { +>!!false : false +>!false : true +>false : false + + g.expando = 1 +>g.expando = 1 : 1 +>g.expando : number +>g : { (): void; expando: number; both: string | number; } +>expando : number +>1 : 1 +} +g.expando // error +>g.expando : number +>g : { (): void; expando: number; both: string | number; } +>expando : number + +if (!!false) { +>!!false : false +>!false : true +>false : false + + g.both = 'hi' +>g.both = 'hi' : "hi" +>g.both : string | number +>g : { (): void; expando: number; both: string | number; } +>both : string | number +>'hi' : "hi" +} +else { + g.both = 0 +>g.both = 0 : 0 +>g.both : string | number +>g : { (): void; expando: number; both: string | number; } +>both : string | number +>0 : 0 +} +g.both +>g.both : string | number +>g : { (): void; expando: number; both: string | number; } +>both : string | number + diff --git a/tests/baselines/reference/typeFromPropertyAssignment37.symbols b/tests/baselines/reference/typeFromPropertyAssignment37.symbols new file mode 100644 index 00000000000..4d2af775b00 --- /dev/null +++ b/tests/baselines/reference/typeFromPropertyAssignment37.symbols @@ -0,0 +1,34 @@ +=== tests/cases/conformance/salsa/use.js === +const util = require('./mod') +>util : Symbol(util, Decl(use.js, 0, 5)) +>require : Symbol(require) +>'./mod' : Symbol("tests/cases/conformance/salsa/mod", Decl(mod.js, 0, 0)) + +function n() { +>n : Symbol(n, Decl(use.js, 0, 29)) + + util.existy // no error +>util.existy : Symbol(existy, Decl(mod.js, 1, 14)) +>util : Symbol(util, Decl(use.js, 0, 5)) +>existy : Symbol(existy, Decl(mod.js, 1, 14)) +} +util.existy // no error +>util.existy : Symbol(existy, Decl(mod.js, 1, 14)) +>util : Symbol(util, Decl(use.js, 0, 5)) +>existy : Symbol(existy, Decl(mod.js, 1, 14)) + +=== tests/cases/conformance/salsa/mod.js === +const util = exports = module.exports = {} +>util : Symbol(util, Decl(mod.js, 0, 5)) +>exports : Symbol("tests/cases/conformance/salsa/mod", Decl(mod.js, 0, 0)) +>module.exports : Symbol("tests/cases/conformance/salsa/mod", Decl(mod.js, 0, 0)) +>module : Symbol(module, Decl(mod.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/salsa/mod", Decl(mod.js, 0, 0)) + +if (!!false) { + util.existy = function () { } +>util.existy : Symbol(existy, Decl(mod.js, 1, 14)) +>util : Symbol(util, Decl(mod.js, 0, 5)) +>existy : Symbol(existy, Decl(mod.js, 1, 14)) +} + diff --git a/tests/baselines/reference/typeFromPropertyAssignment37.types b/tests/baselines/reference/typeFromPropertyAssignment37.types new file mode 100644 index 00000000000..b7355cbecf2 --- /dev/null +++ b/tests/baselines/reference/typeFromPropertyAssignment37.types @@ -0,0 +1,44 @@ +=== tests/cases/conformance/salsa/use.js === +const util = require('./mod') +>util : typeof import("tests/cases/conformance/salsa/mod") +>require('./mod') : typeof import("tests/cases/conformance/salsa/mod") +>require : any +>'./mod' : "./mod" + +function n() { +>n : () => void + + util.existy // no error +>util.existy : () => void +>util : typeof import("tests/cases/conformance/salsa/mod") +>existy : () => void +} +util.existy // no error +>util.existy : () => void +>util : typeof import("tests/cases/conformance/salsa/mod") +>existy : () => void + +=== tests/cases/conformance/salsa/mod.js === +const util = exports = module.exports = {} +>util : typeof import("tests/cases/conformance/salsa/mod") +>exports = module.exports = {} : typeof import("tests/cases/conformance/salsa/mod") +>exports : typeof import("tests/cases/conformance/salsa/mod") +>module.exports = {} : typeof import("tests/cases/conformance/salsa/mod") +>module.exports : typeof import("tests/cases/conformance/salsa/mod") +>module : { "tests/cases/conformance/salsa/mod": typeof import("tests/cases/conformance/salsa/mod"); } +>exports : typeof import("tests/cases/conformance/salsa/mod") +>{} : {} + +if (!!false) { +>!!false : boolean +>!false : true +>false : false + + util.existy = function () { } +>util.existy = function () { } : () => void +>util.existy : () => void +>util : typeof import("tests/cases/conformance/salsa/mod") +>existy : () => void +>function () { } : () => void +} + diff --git a/tests/baselines/reference/typeFromPrototypeAssignment.errors.txt b/tests/baselines/reference/typeFromPrototypeAssignment.errors.txt new file mode 100644 index 00000000000..edd3435c445 --- /dev/null +++ b/tests/baselines/reference/typeFromPrototypeAssignment.errors.txt @@ -0,0 +1,45 @@ +tests/cases/conformance/salsa/a.js(27,20): error TS2339: Property 'addon' does not exist on type '{ set: () => void; get(): void; }'. + + +==== tests/cases/conformance/salsa/a.js (1 errors) ==== + // all references to _map, set, get, addon should be ok + + /** @constructor */ + var Multimap = function() { + this._map = {}; + this._map + this.set + this.get + this.addon + }; + + Multimap.prototype = { + set: function() { + this._map + this.set + this.get + this.addon + }, + get() { + this._map + this.set + this.get + this.addon + } + } + + Multimap.prototype.addon = function () { + ~~~~~ +!!! error TS2339: Property 'addon' does not exist on type '{ set: () => void; get(): void; }'. + this._map + this.set + this.get + this.addon + } + + var mm = new Multimap(); + mm._map + mm.set + mm.get + mm.addon + \ No newline at end of file diff --git a/tests/baselines/reference/typeFromPrototypeAssignment.symbols b/tests/baselines/reference/typeFromPrototypeAssignment.symbols new file mode 100644 index 00000000000..d51382a639f --- /dev/null +++ b/tests/baselines/reference/typeFromPrototypeAssignment.symbols @@ -0,0 +1,122 @@ +=== tests/cases/conformance/salsa/a.js === +// all references to _map, set, get, addon should be ok + +/** @constructor */ +var Multimap = function() { +>Multimap : Symbol(Multimap, Decl(a.js, 3, 3), Decl(a.js, 9, 2)) + + this._map = {}; +>this._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + + this.set +>this.set : Symbol(set, Decl(a.js, 11, 22)) +>set : Symbol(set, Decl(a.js, 11, 22)) + + this.get +>this.get : Symbol(get, Decl(a.js, 17, 6)) +>get : Symbol(get, Decl(a.js, 17, 6)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) + +}; + +Multimap.prototype = { +>Multimap.prototype : Symbol(Multimap.prototype, Decl(a.js, 9, 2)) +>Multimap : Symbol(Multimap, Decl(a.js, 3, 3), Decl(a.js, 9, 2)) +>prototype : Symbol(Multimap.prototype, Decl(a.js, 9, 2)) + + set: function() { +>set : Symbol(set, Decl(a.js, 11, 22)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + + this.set +>this.set : Symbol(set, Decl(a.js, 11, 22)) +>set : Symbol(set, Decl(a.js, 11, 22)) + + this.get +>this.get : Symbol(get, Decl(a.js, 17, 6)) +>get : Symbol(get, Decl(a.js, 17, 6)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) + + }, + get() { +>get : Symbol(get, Decl(a.js, 17, 6)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + + this.set +>this.set : Symbol(set, Decl(a.js, 11, 22)) +>set : Symbol(set, Decl(a.js, 11, 22)) + + this.get +>this.get : Symbol(get, Decl(a.js, 17, 6)) +>get : Symbol(get, Decl(a.js, 17, 6)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) + } +} + +Multimap.prototype.addon = function () { +>Multimap.prototype : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>Multimap : Symbol(Multimap, Decl(a.js, 3, 3), Decl(a.js, 9, 2)) +>prototype : Symbol(Multimap.prototype, Decl(a.js, 9, 2)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + + this.set +>this.set : Symbol(set, Decl(a.js, 11, 22)) +>set : Symbol(set, Decl(a.js, 11, 22)) + + this.get +>this.get : Symbol(get, Decl(a.js, 17, 6)) +>get : Symbol(get, Decl(a.js, 17, 6)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +} + +var mm = new Multimap(); +>mm : Symbol(mm, Decl(a.js, 33, 3)) +>Multimap : Symbol(Multimap, Decl(a.js, 3, 3), Decl(a.js, 9, 2)) + +mm._map +>mm._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>mm : Symbol(mm, Decl(a.js, 33, 3)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + +mm.set +>mm.set : Symbol(set, Decl(a.js, 11, 22)) +>mm : Symbol(mm, Decl(a.js, 33, 3)) +>set : Symbol(set, Decl(a.js, 11, 22)) + +mm.get +>mm.get : Symbol(get, Decl(a.js, 17, 6)) +>mm : Symbol(mm, Decl(a.js, 33, 3)) +>get : Symbol(get, Decl(a.js, 17, 6)) + +mm.addon +>mm.addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>mm : Symbol(mm, Decl(a.js, 33, 3)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) + diff --git a/tests/baselines/reference/typeFromPrototypeAssignment.types b/tests/baselines/reference/typeFromPrototypeAssignment.types new file mode 100644 index 00000000000..87e4be5e0b9 --- /dev/null +++ b/tests/baselines/reference/typeFromPrototypeAssignment.types @@ -0,0 +1,149 @@ +=== tests/cases/conformance/salsa/a.js === +// all references to _map, set, get, addon should be ok + +/** @constructor */ +var Multimap = function() { +>Multimap : typeof Multimap +>function() { this._map = {}; this._map this.set this.get this.addon} : typeof Multimap + + this._map = {}; +>this._map = {} : {} +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} +>{} : {} + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void + +}; + +Multimap.prototype = { +>Multimap.prototype = { set: function() { this._map this.set this.get this.addon }, get() { this._map this.set this.get this.addon }} : { set: () => void; get(): void; } +>Multimap.prototype : { set: () => void; get(): void; } +>Multimap : typeof Multimap +>prototype : { set: () => void; get(): void; } +>{ set: function() { this._map this.set this.get this.addon }, get() { this._map this.set this.get this.addon }} : { set: () => void; get(): void; } + + set: function() { +>set : () => void +>function() { this._map this.set this.get this.addon } : () => void + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void + + }, + get() { +>get : () => void + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void + } +} + +Multimap.prototype.addon = function () { +>Multimap.prototype.addon = function () { this._map this.set this.get this.addon} : () => void +>Multimap.prototype.addon : any +>Multimap.prototype : { set: () => void; get(): void; } +>Multimap : typeof Multimap +>prototype : { set: () => void; get(): void; } +>addon : any +>function () { this._map this.set this.get this.addon} : () => void + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void +} + +var mm = new Multimap(); +>mm : Multimap & { set: () => void; get(): void; } +>new Multimap() : Multimap & { set: () => void; get(): void; } +>Multimap : typeof Multimap + +mm._map +>mm._map : {} +>mm : Multimap & { set: () => void; get(): void; } +>_map : {} + +mm.set +>mm.set : () => void +>mm : Multimap & { set: () => void; get(): void; } +>set : () => void + +mm.get +>mm.get : () => void +>mm : Multimap & { set: () => void; get(): void; } +>get : () => void + +mm.addon +>mm.addon : () => void +>mm : Multimap & { set: () => void; get(): void; } +>addon : () => void + diff --git a/tests/baselines/reference/typeFromPrototypeAssignment2.errors.txt b/tests/baselines/reference/typeFromPrototypeAssignment2.errors.txt new file mode 100644 index 00000000000..d4f66132d44 --- /dev/null +++ b/tests/baselines/reference/typeFromPrototypeAssignment2.errors.txt @@ -0,0 +1,47 @@ +tests/cases/conformance/salsa/a.js(28,24): error TS2339: Property 'addon' does not exist on type '{ set: () => void; get(): void; }'. + + +==== tests/cases/conformance/salsa/a.js (1 errors) ==== + // non top-level: + // all references to _map, set, get, addon should be ok + (function container() { + /** @constructor */ + var Multimap = function() { + this._map = {}; + this._map + this.set + this.get + this.addon + }; + + Multimap.prototype = { + set: function() { + this._map + this.set + this.get + this.addon + }, + get() { + this._map + this.set + this.get + this.addon + } + } + + Multimap.prototype.addon = function () { + ~~~~~ +!!! error TS2339: Property 'addon' does not exist on type '{ set: () => void; get(): void; }'. + this._map + this.set + this.get + this.addon + } + + var mm = new Multimap(); + mm._map + mm.set + mm.get + mm.addon + }); + \ No newline at end of file diff --git a/tests/baselines/reference/typeFromPrototypeAssignment2.symbols b/tests/baselines/reference/typeFromPrototypeAssignment2.symbols new file mode 100644 index 00000000000..25ae9e31c69 --- /dev/null +++ b/tests/baselines/reference/typeFromPrototypeAssignment2.symbols @@ -0,0 +1,127 @@ +=== tests/cases/conformance/salsa/a.js === +// non top-level: +// all references to _map, set, get, addon should be ok +(function container() { +>container : Symbol(container, Decl(a.js, 2, 1)) + + /** @constructor */ + var Multimap = function() { +>Multimap : Symbol(Multimap, Decl(a.js, 4, 7)) + + this._map = {}; +>this._map : Symbol(Multimap._map, Decl(a.js, 4, 31)) +>_map : Symbol(Multimap._map, Decl(a.js, 4, 31)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 4, 31)) +>_map : Symbol(Multimap._map, Decl(a.js, 4, 31)) + + this.set +>this.set : Symbol(set, Decl(a.js, 12, 26)) +>set : Symbol(set, Decl(a.js, 12, 26)) + + this.get +>this.get : Symbol(get, Decl(a.js, 18, 10)) +>get : Symbol(get, Decl(a.js, 18, 10)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) +>addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) + + }; + + Multimap.prototype = { +>Multimap.prototype : Symbol(Multimap.prototype, Decl(a.js, 10, 6)) +>Multimap : Symbol(Multimap, Decl(a.js, 4, 7)) +>prototype : Symbol(Multimap.prototype, Decl(a.js, 10, 6)) + + set: function() { +>set : Symbol(set, Decl(a.js, 12, 26)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 4, 31)) +>_map : Symbol(Multimap._map, Decl(a.js, 4, 31)) + + this.set +>this.set : Symbol(set, Decl(a.js, 12, 26)) +>set : Symbol(set, Decl(a.js, 12, 26)) + + this.get +>this.get : Symbol(get, Decl(a.js, 18, 10)) +>get : Symbol(get, Decl(a.js, 18, 10)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) +>addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) + + }, + get() { +>get : Symbol(get, Decl(a.js, 18, 10)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 4, 31)) +>_map : Symbol(Multimap._map, Decl(a.js, 4, 31)) + + this.set +>this.set : Symbol(set, Decl(a.js, 12, 26)) +>set : Symbol(set, Decl(a.js, 12, 26)) + + this.get +>this.get : Symbol(get, Decl(a.js, 18, 10)) +>get : Symbol(get, Decl(a.js, 18, 10)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) +>addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) + } + } + + Multimap.prototype.addon = function () { +>Multimap.prototype : Symbol(Multimap.addon, Decl(a.js, 25, 5)) +>Multimap : Symbol(Multimap, Decl(a.js, 4, 7)) +>prototype : Symbol(Multimap.prototype, Decl(a.js, 10, 6)) +>addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 4, 31)) +>_map : Symbol(Multimap._map, Decl(a.js, 4, 31)) + + this.set +>this.set : Symbol(set, Decl(a.js, 12, 26)) +>set : Symbol(set, Decl(a.js, 12, 26)) + + this.get +>this.get : Symbol(get, Decl(a.js, 18, 10)) +>get : Symbol(get, Decl(a.js, 18, 10)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) +>addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) + } + + var mm = new Multimap(); +>mm : Symbol(mm, Decl(a.js, 34, 7)) +>Multimap : Symbol(Multimap, Decl(a.js, 4, 7)) + + mm._map +>mm._map : Symbol(Multimap._map, Decl(a.js, 4, 31)) +>mm : Symbol(mm, Decl(a.js, 34, 7)) +>_map : Symbol(Multimap._map, Decl(a.js, 4, 31)) + + mm.set +>mm.set : Symbol(set, Decl(a.js, 12, 26)) +>mm : Symbol(mm, Decl(a.js, 34, 7)) +>set : Symbol(set, Decl(a.js, 12, 26)) + + mm.get +>mm.get : Symbol(get, Decl(a.js, 18, 10)) +>mm : Symbol(mm, Decl(a.js, 34, 7)) +>get : Symbol(get, Decl(a.js, 18, 10)) + + mm.addon +>mm.addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) +>mm : Symbol(mm, Decl(a.js, 34, 7)) +>addon : Symbol(Multimap.addon, Decl(a.js, 25, 5)) + +}); + diff --git a/tests/baselines/reference/typeFromPrototypeAssignment2.types b/tests/baselines/reference/typeFromPrototypeAssignment2.types new file mode 100644 index 00000000000..d37f421a356 --- /dev/null +++ b/tests/baselines/reference/typeFromPrototypeAssignment2.types @@ -0,0 +1,156 @@ +=== tests/cases/conformance/salsa/a.js === +// non top-level: +// all references to _map, set, get, addon should be ok +(function container() { +>(function container() { /** @constructor */ var Multimap = function() { this._map = {}; this._map this.set this.get this.addon }; Multimap.prototype = { set: function() { this._map this.set this.get this.addon }, get() { this._map this.set this.get this.addon } } Multimap.prototype.addon = function () { this._map this.set this.get this.addon } var mm = new Multimap(); mm._map mm.set mm.get mm.addon}) : () => void +>function container() { /** @constructor */ var Multimap = function() { this._map = {}; this._map this.set this.get this.addon }; Multimap.prototype = { set: function() { this._map this.set this.get this.addon }, get() { this._map this.set this.get this.addon } } Multimap.prototype.addon = function () { this._map this.set this.get this.addon } var mm = new Multimap(); mm._map mm.set mm.get mm.addon} : () => void +>container : () => void + + /** @constructor */ + var Multimap = function() { +>Multimap : typeof Multimap +>function() { this._map = {}; this._map this.set this.get this.addon } : typeof Multimap + + this._map = {}; +>this._map = {} : {} +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} +>{} : {} + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void + + }; + + Multimap.prototype = { +>Multimap.prototype = { set: function() { this._map this.set this.get this.addon }, get() { this._map this.set this.get this.addon } } : { set: () => void; get(): void; } +>Multimap.prototype : { set: () => void; get(): void; } +>Multimap : typeof Multimap +>prototype : { set: () => void; get(): void; } +>{ set: function() { this._map this.set this.get this.addon }, get() { this._map this.set this.get this.addon } } : { set: () => void; get(): void; } + + set: function() { +>set : () => void +>function() { this._map this.set this.get this.addon } : () => void + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void + + }, + get() { +>get : () => void + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void + } + } + + Multimap.prototype.addon = function () { +>Multimap.prototype.addon = function () { this._map this.set this.get this.addon } : () => void +>Multimap.prototype.addon : any +>Multimap.prototype : { set: () => void; get(): void; } +>Multimap : typeof Multimap +>prototype : { set: () => void; get(): void; } +>addon : any +>function () { this._map this.set this.get this.addon } : () => void + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void + } + + var mm = new Multimap(); +>mm : Multimap & { set: () => void; get(): void; } +>new Multimap() : Multimap & { set: () => void; get(): void; } +>Multimap : typeof Multimap + + mm._map +>mm._map : {} +>mm : Multimap & { set: () => void; get(): void; } +>_map : {} + + mm.set +>mm.set : () => void +>mm : Multimap & { set: () => void; get(): void; } +>set : () => void + + mm.get +>mm.get : () => void +>mm : Multimap & { set: () => void; get(): void; } +>get : () => void + + mm.addon +>mm.addon : () => void +>mm : Multimap & { set: () => void; get(): void; } +>addon : () => void + +}); + diff --git a/tests/baselines/reference/typeGuardFunction.js b/tests/baselines/reference/typeGuardFunction.js index 3dc73251d1c..7d762946e30 100644 --- a/tests/baselines/reference/typeGuardFunction.js +++ b/tests/baselines/reference/typeGuardFunction.js @@ -89,7 +89,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeGuardFunctionErrors.js b/tests/baselines/reference/typeGuardFunctionErrors.js index 2a09ec27dd7..69eb02229b9 100644 --- a/tests/baselines/reference/typeGuardFunctionErrors.js +++ b/tests/baselines/reference/typeGuardFunctionErrors.js @@ -174,7 +174,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeGuardFunctionGenerics.js b/tests/baselines/reference/typeGuardFunctionGenerics.js index 91caa3c30e5..13d14fa6bb6 100644 --- a/tests/baselines/reference/typeGuardFunctionGenerics.js +++ b/tests/baselines/reference/typeGuardFunctionGenerics.js @@ -39,7 +39,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeGuardFunctionOfFormThis.js b/tests/baselines/reference/typeGuardFunctionOfFormThis.js index 1651d0e3667..1d52025c9f7 100644 --- a/tests/baselines/reference/typeGuardFunctionOfFormThis.js +++ b/tests/baselines/reference/typeGuardFunctionOfFormThis.js @@ -148,7 +148,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeGuardFunctionOfFormThisErrors.js b/tests/baselines/reference/typeGuardFunctionOfFormThisErrors.js index 4b562e52a91..6db9d7f6885 100644 --- a/tests/baselines/reference/typeGuardFunctionOfFormThisErrors.js +++ b/tests/baselines/reference/typeGuardFunctionOfFormThisErrors.js @@ -66,7 +66,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeGuardOfFormInstanceOf.js b/tests/baselines/reference/typeGuardOfFormInstanceOf.js index 080719fe1c8..554e3c0d572 100644 --- a/tests/baselines/reference/typeGuardOfFormInstanceOf.js +++ b/tests/baselines/reference/typeGuardOfFormInstanceOf.js @@ -79,7 +79,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeGuardOfFormIsType.js b/tests/baselines/reference/typeGuardOfFormIsType.js index 6c2ed2e0827..57c0da2f4e5 100644 --- a/tests/baselines/reference/typeGuardOfFormIsType.js +++ b/tests/baselines/reference/typeGuardOfFormIsType.js @@ -43,7 +43,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeGuardOfFormThisMember.js b/tests/baselines/reference/typeGuardOfFormThisMember.js index 23d982e398c..1d4d9df79e2 100644 --- a/tests/baselines/reference/typeGuardOfFormThisMember.js +++ b/tests/baselines/reference/typeGuardOfFormThisMember.js @@ -89,7 +89,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeGuardOfFormThisMemberErrors.js b/tests/baselines/reference/typeGuardOfFormThisMemberErrors.js index ab49438fbdf..1992c339b32 100644 --- a/tests/baselines/reference/typeGuardOfFormThisMemberErrors.js +++ b/tests/baselines/reference/typeGuardOfFormThisMemberErrors.js @@ -39,7 +39,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types b/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types index 6510b73d44d..4787c07d758 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types @@ -14,7 +14,7 @@ if (typeof a === "number") { let c: number = a; >c : number ->a : number & {} +>a : number } if (typeof a === "string") { >typeof a === "string" : boolean @@ -24,7 +24,7 @@ if (typeof a === "string") { let c: string = a; >c : string ->a : string & {} +>a : string } if (typeof a === "boolean") { >typeof a === "boolean" : boolean @@ -34,7 +34,7 @@ if (typeof a === "boolean") { let c: boolean = a; >c : boolean ->a : (false & {}) | (true & {}) +>a : boolean } if (typeof b === "number") { @@ -45,7 +45,7 @@ if (typeof b === "number") { let c: number = b; >c : number ->b : { toString(): string; } & number +>b : number } if (typeof b === "string") { >typeof b === "string" : boolean @@ -55,7 +55,7 @@ if (typeof b === "string") { let c: string = b; >c : string ->b : { toString(): string; } & string +>b : string } if (typeof b === "boolean") { >typeof b === "boolean" : boolean @@ -65,6 +65,6 @@ if (typeof b === "boolean") { let c: boolean = b; >c : boolean ->b : ({ toString(): string; } & false) | ({ toString(): string; } & true) +>b : boolean } diff --git a/tests/baselines/reference/typeMatch1.errors.txt b/tests/baselines/reference/typeMatch1.errors.txt index 7025fd0c3b2..10a07397f71 100644 --- a/tests/baselines/reference/typeMatch1.errors.txt +++ b/tests/baselines/reference/typeMatch1.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/typeMatch1.ts(18,1): error TS2322: Type 'D' is not assignable to type 'C'. Types have separate declarations of a private property 'x'. -tests/cases/compiler/typeMatch1.ts(19,1): error TS2322: Type 'typeof C' is not assignable to type 'C'. +tests/cases/compiler/typeMatch1.ts(19,4): error TS2322: Type 'typeof C' is not assignable to type 'C'. Property 'x' is missing in type 'typeof C'. tests/cases/compiler/typeMatch1.ts(20,1): error TS2367: This condition will always return 'false' since the types 'typeof C' and 'typeof D' have no overlap. @@ -28,9 +28,10 @@ tests/cases/compiler/typeMatch1.ts(20,1): error TS2367: This condition will alwa !!! error TS2322: Type 'D' is not assignable to type 'C'. !!! error TS2322: Types have separate declarations of a private property 'x'. x6=C; - ~~ + ~ !!! error TS2322: Type 'typeof C' is not assignable to type 'C'. !!! error TS2322: Property 'x' is missing in type 'typeof C'. +!!! related TS6213 tests/cases/compiler/typeMatch1.ts:19:4: Did you mean to use 'new' with this expression? C==D; ~~~~ !!! error TS2367: This condition will always return 'false' since the types 'typeof C' and 'typeof D' have no overlap. diff --git a/tests/baselines/reference/typeMatch2.js b/tests/baselines/reference/typeMatch2.js index 7d7f8bea6a4..cc5073f4563 100644 --- a/tests/baselines/reference/typeMatch2.js +++ b/tests/baselines/reference/typeMatch2.js @@ -51,7 +51,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeOfSuperCall.js b/tests/baselines/reference/typeOfSuperCall.js index 4152ea23eac..88be3876544 100644 --- a/tests/baselines/reference/typeOfSuperCall.js +++ b/tests/baselines/reference/typeOfSuperCall.js @@ -15,7 +15,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeParameterAsBaseClass.js b/tests/baselines/reference/typeParameterAsBaseClass.js index 5d58c78c5c4..8a963309eab 100644 --- a/tests/baselines/reference/typeParameterAsBaseClass.js +++ b/tests/baselines/reference/typeParameterAsBaseClass.js @@ -9,7 +9,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeParameterAsBaseType.js b/tests/baselines/reference/typeParameterAsBaseType.js index 7b5643a6b9d..a6eddf38a38 100644 --- a/tests/baselines/reference/typeParameterAsBaseType.js +++ b/tests/baselines/reference/typeParameterAsBaseType.js @@ -19,7 +19,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeParameterDoesntBlockParameterLookup.js b/tests/baselines/reference/typeParameterDoesntBlockParameterLookup.js new file mode 100644 index 00000000000..90f1a1f4a37 --- /dev/null +++ b/tests/baselines/reference/typeParameterDoesntBlockParameterLookup.js @@ -0,0 +1,4 @@ +//// [typeParameterDoesntBlockParameterLookup.ts] +declare function f(Bar: any): void + +//// [typeParameterDoesntBlockParameterLookup.js] diff --git a/tests/baselines/reference/typeParameterDoesntBlockParameterLookup.symbols b/tests/baselines/reference/typeParameterDoesntBlockParameterLookup.symbols new file mode 100644 index 00000000000..8c98b05e2dd --- /dev/null +++ b/tests/baselines/reference/typeParameterDoesntBlockParameterLookup.symbols @@ -0,0 +1,8 @@ +=== tests/cases/compiler/typeParameterDoesntBlockParameterLookup.ts === +declare function f(Bar: any): void +>f : Symbol(f, Decl(typeParameterDoesntBlockParameterLookup.ts, 0, 0)) +>Foo : Symbol(Foo, Decl(typeParameterDoesntBlockParameterLookup.ts, 0, 19)) +>Bar : Symbol(Bar, Decl(typeParameterDoesntBlockParameterLookup.ts, 0, 35), Decl(typeParameterDoesntBlockParameterLookup.ts, 0, 41)) +>Bar : Symbol(Bar, Decl(typeParameterDoesntBlockParameterLookup.ts, 0, 35), Decl(typeParameterDoesntBlockParameterLookup.ts, 0, 41)) +>Bar : Symbol(Bar, Decl(typeParameterDoesntBlockParameterLookup.ts, 0, 35), Decl(typeParameterDoesntBlockParameterLookup.ts, 0, 41)) + diff --git a/tests/baselines/reference/typeParameterDoesntBlockParameterLookup.types b/tests/baselines/reference/typeParameterDoesntBlockParameterLookup.types new file mode 100644 index 00000000000..7edcbde4373 --- /dev/null +++ b/tests/baselines/reference/typeParameterDoesntBlockParameterLookup.types @@ -0,0 +1,5 @@ +=== tests/cases/compiler/typeParameterDoesntBlockParameterLookup.ts === +declare function f(Bar: any): void +>f : (Bar: any) => void +>Bar : any + diff --git a/tests/baselines/reference/typeParameterExtendingUnion1.js b/tests/baselines/reference/typeParameterExtendingUnion1.js index 04356c8f071..78bcc9f650c 100644 --- a/tests/baselines/reference/typeParameterExtendingUnion1.js +++ b/tests/baselines/reference/typeParameterExtendingUnion1.js @@ -19,7 +19,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeParameterExtendingUnion2.js b/tests/baselines/reference/typeParameterExtendingUnion2.js index 8c47b304598..0a55d8fd0d4 100644 --- a/tests/baselines/reference/typeParameterExtendingUnion2.js +++ b/tests/baselines/reference/typeParameterExtendingUnion2.js @@ -19,7 +19,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeParameterFixingWithContextSensitiveArguments2.errors.txt b/tests/baselines/reference/typeParameterFixingWithContextSensitiveArguments2.errors.txt index 5a6047222ee..e2551020f84 100644 --- a/tests/baselines/reference/typeParameterFixingWithContextSensitiveArguments2.errors.txt +++ b/tests/baselines/reference/typeParameterFixingWithContextSensitiveArguments2.errors.txt @@ -1,6 +1,5 @@ -tests/cases/compiler/typeParameterFixingWithContextSensitiveArguments2.ts(7,25): error TS2345: Argument of type '(x: A) => A' is not assignable to parameter of type '(x: A) => B'. - Type 'A' is not assignable to type 'B'. - Property 'b' is missing in type 'A'. +tests/cases/compiler/typeParameterFixingWithContextSensitiveArguments2.ts(7,30): error TS2322: Type 'A' is not assignable to type 'B'. + Property 'b' is missing in type 'A'. ==== tests/cases/compiler/typeParameterFixingWithContextSensitiveArguments2.ts (1 errors) ==== @@ -11,7 +10,7 @@ tests/cases/compiler/typeParameterFixingWithContextSensitiveArguments2.ts(7,25): var a: A, b: B; var d = f(a, b, x => x, x => x); // A => A not assignable to A => B - ~~~~~~ -!!! error TS2345: Argument of type '(x: A) => A' is not assignable to parameter of type '(x: A) => B'. -!!! error TS2345: Type 'A' is not assignable to type 'B'. -!!! error TS2345: Property 'b' is missing in type 'A'. \ No newline at end of file + ~ +!!! error TS2322: Type 'A' is not assignable to type 'B'. +!!! error TS2322: Property 'b' is missing in type 'A'. +!!! related TS6502 tests/cases/compiler/typeParameterFixingWithContextSensitiveArguments2.ts:1:51: The expected type comes from the return type of this signature. \ No newline at end of file diff --git a/tests/baselines/reference/typeParameterFixingWithContextSensitiveArguments3.errors.txt b/tests/baselines/reference/typeParameterFixingWithContextSensitiveArguments3.errors.txt index cd0801f7ba9..d678fb7f908 100644 --- a/tests/baselines/reference/typeParameterFixingWithContextSensitiveArguments3.errors.txt +++ b/tests/baselines/reference/typeParameterFixingWithContextSensitiveArguments3.errors.txt @@ -1,6 +1,5 @@ -tests/cases/compiler/typeParameterFixingWithContextSensitiveArguments3.ts(7,29): error TS2345: Argument of type '(t2: A) => A' is not assignable to parameter of type '(t2: A) => B'. - Type 'A' is not assignable to type 'B'. - Property 'b' is missing in type 'A'. +tests/cases/compiler/typeParameterFixingWithContextSensitiveArguments3.ts(7,35): error TS2322: Type 'A' is not assignable to type 'B'. + Property 'b' is missing in type 'A'. ==== tests/cases/compiler/typeParameterFixingWithContextSensitiveArguments3.ts (1 errors) ==== @@ -11,7 +10,7 @@ tests/cases/compiler/typeParameterFixingWithContextSensitiveArguments3.ts(7,29): var a: A, b: B; var d = f(a, b, u2 => u2.b, t2 => t2); - ~~~~~~~~ -!!! error TS2345: Argument of type '(t2: A) => A' is not assignable to parameter of type '(t2: A) => B'. -!!! error TS2345: Type 'A' is not assignable to type 'B'. -!!! error TS2345: Property 'b' is missing in type 'A'. \ No newline at end of file + ~~ +!!! error TS2322: Type 'A' is not assignable to type 'B'. +!!! error TS2322: Property 'b' is missing in type 'A'. +!!! related TS6502 tests/cases/compiler/typeParameterFixingWithContextSensitiveArguments3.ts:1:56: The expected type comes from the return type of this signature. \ No newline at end of file diff --git a/tests/baselines/reference/typeRelationships.js b/tests/baselines/reference/typeRelationships.js index 70920ae298b..27ba221a281 100644 --- a/tests/baselines/reference/typeRelationships.js +++ b/tests/baselines/reference/typeRelationships.js @@ -47,7 +47,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeTagCircularReferenceOnConstructorFunction.errors.txt b/tests/baselines/reference/typeTagCircularReferenceOnConstructorFunction.errors.txt new file mode 100644 index 00000000000..2469e647685 --- /dev/null +++ b/tests/baselines/reference/typeTagCircularReferenceOnConstructorFunction.errors.txt @@ -0,0 +1,15 @@ +tests/cases/conformance/jsdoc/bug27346.js(2,4): error TS8030: The type of a function declaration must match the function's signature. +tests/cases/conformance/jsdoc/bug27346.js(2,11): error TS2587: JSDoc type 'MyClass' circularly references itself. + + +==== tests/cases/conformance/jsdoc/bug27346.js (2 errors) ==== + /** + * @type {MyClass} + ~~~~~~~~~~~~~~~ +!!! error TS8030: The type of a function declaration must match the function's signature. + ~~~~~~~ +!!! error TS2587: JSDoc type 'MyClass' circularly references itself. + */ + function MyClass() { } + MyClass.prototype = {}; + \ No newline at end of file diff --git a/tests/baselines/reference/typeTagCircularReferenceOnConstructorFunction.symbols b/tests/baselines/reference/typeTagCircularReferenceOnConstructorFunction.symbols new file mode 100644 index 00000000000..bdbd4ee1b05 --- /dev/null +++ b/tests/baselines/reference/typeTagCircularReferenceOnConstructorFunction.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/jsdoc/bug27346.js === +/** + * @type {MyClass} + */ +function MyClass() { } +>MyClass : Symbol(MyClass, Decl(bug27346.js, 0, 0), Decl(bug27346.js, 3, 22)) + +MyClass.prototype = {}; +>MyClass.prototype : Symbol(MyClass.prototype, Decl(bug27346.js, 3, 22)) +>MyClass : Symbol(MyClass, Decl(bug27346.js, 0, 0), Decl(bug27346.js, 3, 22)) +>prototype : Symbol(MyClass.prototype, Decl(bug27346.js, 3, 22)) + diff --git a/tests/baselines/reference/typeTagCircularReferenceOnConstructorFunction.types b/tests/baselines/reference/typeTagCircularReferenceOnConstructorFunction.types new file mode 100644 index 00000000000..901fca39955 --- /dev/null +++ b/tests/baselines/reference/typeTagCircularReferenceOnConstructorFunction.types @@ -0,0 +1,14 @@ +=== tests/cases/conformance/jsdoc/bug27346.js === +/** + * @type {MyClass} + */ +function MyClass() { } +>MyClass : typeof MyClass + +MyClass.prototype = {}; +>MyClass.prototype = {} : {} +>MyClass.prototype : {} +>MyClass : typeof MyClass +>prototype : {} +>{} : {} + diff --git a/tests/baselines/reference/typeValueConflict1.js b/tests/baselines/reference/typeValueConflict1.js index f1efa5a6318..074e73ea014 100644 --- a/tests/baselines/reference/typeValueConflict1.js +++ b/tests/baselines/reference/typeValueConflict1.js @@ -18,7 +18,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeValueConflict2.js b/tests/baselines/reference/typeValueConflict2.js index 24d39bf723a..534dfa1cdff 100644 --- a/tests/baselines/reference/typeValueConflict2.js +++ b/tests/baselines/reference/typeValueConflict2.js @@ -25,7 +25,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typeVariableTypeGuards.js b/tests/baselines/reference/typeVariableTypeGuards.js index 7c7692e9d8c..385c8bd55c4 100644 --- a/tests/baselines/reference/typeVariableTypeGuards.js +++ b/tests/baselines/reference/typeVariableTypeGuards.js @@ -91,7 +91,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typecheckIfCondition.errors.txt b/tests/baselines/reference/typecheckIfCondition.errors.txt index 3f23c71d247..e9c3707583e 100644 --- a/tests/baselines/reference/typecheckIfCondition.errors.txt +++ b/tests/baselines/reference/typecheckIfCondition.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/typecheckIfCondition.ts(4,10): error TS2304: Cannot find name 'module'. -tests/cases/compiler/typecheckIfCondition.ts(4,26): error TS2304: Cannot find name 'module'. +tests/cases/compiler/typecheckIfCondition.ts(4,10): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/typecheckIfCondition.ts(4,26): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ==== tests/cases/compiler/typecheckIfCondition.ts (2 errors) ==== @@ -8,9 +8,9 @@ tests/cases/compiler/typecheckIfCondition.ts(4,26): error TS2304: Cannot find na { if (!module.exports) module.exports = ""; ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. var x = null; // don't want to baseline output } \ No newline at end of file diff --git a/tests/baselines/reference/typedefCrossModule5.errors.txt b/tests/baselines/reference/typedefCrossModule5.errors.txt index b75652a31d5..2784f0e1896 100644 --- a/tests/baselines/reference/typedefCrossModule5.errors.txt +++ b/tests/baselines/reference/typedefCrossModule5.errors.txt @@ -1,38 +1,38 @@ tests/cases/conformance/jsdoc/mod1.js:1:23 - error TS2300: Duplicate identifier 'Foo'. -1 /** @typedef {number} Foo */ -   ~~~ +1 /** @typedef {number} Foo */ +   ~~~ tests/cases/conformance/jsdoc/mod2.js:1:7 - 1 class Foo { } // should error -    ~~~ + 1 class Foo { } // should error +    ~~~ 'Foo' was also declared here. tests/cases/conformance/jsdoc/mod1.js:2:7 - error TS2451: Cannot redeclare block-scoped variable 'Bar'. -2 class Bar {} -   ~~~ +2 class Bar {} +   ~~~ tests/cases/conformance/jsdoc/mod2.js:2:7 - 2 const Bar = 3; -    ~~~ + 2 const Bar = 3; +    ~~~ 'Bar' was also declared here. tests/cases/conformance/jsdoc/mod2.js:1:7 - error TS2300: Duplicate identifier 'Foo'. -1 class Foo { } // should error -   ~~~ +1 class Foo { } // should error +   ~~~ tests/cases/conformance/jsdoc/mod1.js:1:23 - 1 /** @typedef {number} Foo */ -    ~~~ + 1 /** @typedef {number} Foo */ +    ~~~ 'Foo' was also declared here. tests/cases/conformance/jsdoc/mod2.js:2:7 - error TS2451: Cannot redeclare block-scoped variable 'Bar'. -2 const Bar = 3; -   ~~~ +2 const Bar = 3; +   ~~~ tests/cases/conformance/jsdoc/mod1.js:2:7 - 2 class Bar {} -    ~~~ + 2 class Bar {} +    ~~~ 'Bar' was also declared here. diff --git a/tests/baselines/reference/typeofClass2.js b/tests/baselines/reference/typeofClass2.js index 12bfd1126f0..e145a5d9b45 100644 --- a/tests/baselines/reference/typeofClass2.js +++ b/tests/baselines/reference/typeofClass2.js @@ -28,7 +28,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/types.forAwait.esnext.1.symbols b/tests/baselines/reference/types.forAwait.esnext.1.symbols index 286f0a8555c..c3c10c42109 100644 --- a/tests/baselines/reference/types.forAwait.esnext.1.symbols +++ b/tests/baselines/reference/types.forAwait.esnext.1.symbols @@ -7,49 +7,70 @@ declare const iterable: Iterable; >iterable : Symbol(iterable, Decl(types.forAwait.esnext.1.ts, 1, 13)) >Iterable : Symbol(Iterable, Decl(lib.es2015.iterable.d.ts, --, --)) +declare const iterableOfPromise: Iterable>; +>iterableOfPromise : Symbol(iterableOfPromise, Decl(types.forAwait.esnext.1.ts, 2, 13)) +>Iterable : Symbol(Iterable, Decl(lib.es2015.iterable.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) + async function f1() { ->f1 : Symbol(f1, Decl(types.forAwait.esnext.1.ts, 1, 41)) +>f1 : Symbol(f1, Decl(types.forAwait.esnext.1.ts, 2, 59)) let y: number; ->y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 3, 7)) +>y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 4, 7)) for await (const x of asyncIterable) { ->x : Symbol(x, Decl(types.forAwait.esnext.1.ts, 4, 20)) +>x : Symbol(x, Decl(types.forAwait.esnext.1.ts, 5, 20)) >asyncIterable : Symbol(asyncIterable, Decl(types.forAwait.esnext.1.ts, 0, 13)) } for await (const x of iterable) { ->x : Symbol(x, Decl(types.forAwait.esnext.1.ts, 6, 20)) +>x : Symbol(x, Decl(types.forAwait.esnext.1.ts, 7, 20)) >iterable : Symbol(iterable, Decl(types.forAwait.esnext.1.ts, 1, 13)) + } + for await (const x of iterableOfPromise) { +>x : Symbol(x, Decl(types.forAwait.esnext.1.ts, 9, 20)) +>iterableOfPromise : Symbol(iterableOfPromise, Decl(types.forAwait.esnext.1.ts, 2, 13)) } for await (y of asyncIterable) { ->y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 3, 7)) +>y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 4, 7)) >asyncIterable : Symbol(asyncIterable, Decl(types.forAwait.esnext.1.ts, 0, 13)) } for await (y of iterable) { ->y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 3, 7)) +>y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 4, 7)) >iterable : Symbol(iterable, Decl(types.forAwait.esnext.1.ts, 1, 13)) } + for await (y of iterableOfPromise) { +>y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 4, 7)) +>iterableOfPromise : Symbol(iterableOfPromise, Decl(types.forAwait.esnext.1.ts, 2, 13)) + } } async function * f2() { ->f2 : Symbol(f2, Decl(types.forAwait.esnext.1.ts, 12, 1)) +>f2 : Symbol(f2, Decl(types.forAwait.esnext.1.ts, 17, 1)) let y: number; ->y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 14, 7)) +>y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 19, 7)) for await (const x of asyncIterable) { ->x : Symbol(x, Decl(types.forAwait.esnext.1.ts, 15, 20)) +>x : Symbol(x, Decl(types.forAwait.esnext.1.ts, 20, 20)) >asyncIterable : Symbol(asyncIterable, Decl(types.forAwait.esnext.1.ts, 0, 13)) } for await (const x of iterable) { ->x : Symbol(x, Decl(types.forAwait.esnext.1.ts, 17, 20)) +>x : Symbol(x, Decl(types.forAwait.esnext.1.ts, 22, 20)) >iterable : Symbol(iterable, Decl(types.forAwait.esnext.1.ts, 1, 13)) + } + for await (const x of iterableOfPromise) { +>x : Symbol(x, Decl(types.forAwait.esnext.1.ts, 24, 20)) +>iterableOfPromise : Symbol(iterableOfPromise, Decl(types.forAwait.esnext.1.ts, 2, 13)) } for await (y of asyncIterable) { ->y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 14, 7)) +>y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 19, 7)) >asyncIterable : Symbol(asyncIterable, Decl(types.forAwait.esnext.1.ts, 0, 13)) } for await (y of iterable) { ->y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 14, 7)) +>y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 19, 7)) >iterable : Symbol(iterable, Decl(types.forAwait.esnext.1.ts, 1, 13)) } + for await (y of iterableOfPromise) { +>y : Symbol(y, Decl(types.forAwait.esnext.1.ts, 19, 7)) +>iterableOfPromise : Symbol(iterableOfPromise, Decl(types.forAwait.esnext.1.ts, 2, 13)) + } } diff --git a/tests/baselines/reference/types.forAwait.esnext.1.types b/tests/baselines/reference/types.forAwait.esnext.1.types index f001b39a071..69403b40593 100644 --- a/tests/baselines/reference/types.forAwait.esnext.1.types +++ b/tests/baselines/reference/types.forAwait.esnext.1.types @@ -5,6 +5,9 @@ declare const asyncIterable: AsyncIterable; declare const iterable: Iterable; >iterable : Iterable +declare const iterableOfPromise: Iterable>; +>iterableOfPromise : Iterable> + async function f1() { >f1 : () => Promise @@ -18,6 +21,10 @@ async function f1() { for await (const x of iterable) { >x : number >iterable : Iterable + } + for await (const x of iterableOfPromise) { +>x : number +>iterableOfPromise : Iterable> } for await (y of asyncIterable) { >y : number @@ -27,6 +34,10 @@ async function f1() { >y : number >iterable : Iterable } + for await (y of iterableOfPromise) { +>y : number +>iterableOfPromise : Iterable> + } } async function * f2() { >f2 : () => AsyncIterableIterator @@ -41,6 +52,10 @@ async function * f2() { for await (const x of iterable) { >x : number >iterable : Iterable + } + for await (const x of iterableOfPromise) { +>x : number +>iterableOfPromise : Iterable> } for await (y of asyncIterable) { >y : number @@ -50,4 +65,8 @@ async function * f2() { >y : number >iterable : Iterable } + for await (y of iterableOfPromise) { +>y : number +>iterableOfPromise : Iterable> + } } diff --git a/tests/baselines/reference/typesVersions.ambientModules.js b/tests/baselines/reference/typesVersions.ambientModules.js new file mode 100644 index 00000000000..7dee6e9e3fd --- /dev/null +++ b/tests/baselines/reference/typesVersions.ambientModules.js @@ -0,0 +1,43 @@ +//// [tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +//// [index.d.ts] +declare module "ext" { + export const a = "default a"; +} +declare module "ext/other" { + export const b = "default b"; +} + +//// [index.d.ts] +declare module "ext" { + export const a = "ts3.1 a"; +} +declare module "ext/other" { + export const b = "ts3.1 b"; +} + +//// [main.ts] +import { a } from "ext"; +import { b } from "ext/other"; + +const aa: "ts3.1 a" = a; +const bb: "ts3.1 b" = b; + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +const aa = ext_1.a; +const bb = other_1.b; diff --git a/tests/baselines/reference/typesVersions.ambientModules.symbols b/tests/baselines/reference/typesVersions.ambientModules.symbols new file mode 100644 index 00000000000..91d1adacd9c --- /dev/null +++ b/tests/baselines/reference/typesVersions.ambientModules.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/moduleResolution/main.ts === +import { a } from "ext"; +>a : Symbol(a, Decl(main.ts, 0, 8)) + +import { b } from "ext/other"; +>b : Symbol(b, Decl(main.ts, 1, 8)) + +const aa: "ts3.1 a" = a; +>aa : Symbol(aa, Decl(main.ts, 3, 5)) +>a : Symbol(a, Decl(main.ts, 0, 8)) + +const bb: "ts3.1 b" = b; +>bb : Symbol(bb, Decl(main.ts, 4, 5)) +>b : Symbol(b, Decl(main.ts, 1, 8)) + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts === +declare module "ext" { +>"ext" : Symbol("ext", Decl(index.d.ts, 0, 0)) + + export const a = "ts3.1 a"; +>a : Symbol(a, Decl(index.d.ts, 1, 16)) +} +declare module "ext/other" { +>"ext/other" : Symbol("ext/other", Decl(index.d.ts, 2, 1)) + + export const b = "ts3.1 b"; +>b : Symbol(b, Decl(index.d.ts, 4, 16)) +} + diff --git a/tests/baselines/reference/typesVersions.ambientModules.trace.json b/tests/baselines/reference/typesVersions.ambientModules.trace.json new file mode 100644 index 00000000000..ad73f88a8ef --- /dev/null +++ b/tests/baselines/reference/typesVersions.ambientModules.trace.json @@ -0,0 +1,63 @@ +[ + "======== Resolving module 'ext' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts' does not exist.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other/ts3.1/index', target file type 'TypeScript'.", + "Directory 'tests/cases/conformance/moduleResolution/node_modules/@types' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/node_modules' does not exist, skipping all lookups in it.", + "Directory 'node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.js' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.jsx' does not exist.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other/ts3.1/index', target file type 'JavaScript'.", + "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/node_modules' does not exist, skipping all lookups in it.", + "Directory 'node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name 'ext/other' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersions.ambientModules.types b/tests/baselines/reference/typesVersions.ambientModules.types new file mode 100644 index 00000000000..0e81bad67a0 --- /dev/null +++ b/tests/baselines/reference/typesVersions.ambientModules.types @@ -0,0 +1,31 @@ +=== tests/cases/conformance/moduleResolution/main.ts === +import { a } from "ext"; +>a : "ts3.1 a" + +import { b } from "ext/other"; +>b : "ts3.1 b" + +const aa: "ts3.1 a" = a; +>aa : "ts3.1 a" +>a : "ts3.1 a" + +const bb: "ts3.1 b" = b; +>bb : "ts3.1 b" +>b : "ts3.1 b" + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts === +declare module "ext" { +>"ext" : typeof import("ext") + + export const a = "ts3.1 a"; +>a : "ts3.1 a" +>"ts3.1 a" : "ts3.1 a" +} +declare module "ext/other" { +>"ext/other" : typeof import("ext/other") + + export const b = "ts3.1 b"; +>b : "ts3.1 b" +>"ts3.1 b" : "ts3.1 b" +} + diff --git a/tests/baselines/reference/typesVersions.justIndex.js b/tests/baselines/reference/typesVersions.justIndex.js new file mode 100644 index 00000000000..094376c7d0f --- /dev/null +++ b/tests/baselines/reference/typesVersions.justIndex.js @@ -0,0 +1,19 @@ +//// [tests/cases/conformance/moduleResolution/typesVersions.justIndex.ts] //// + +//// [package.json] +{ + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +//// [index.d.ts] +export const a = 0; + +//// [user.ts] +import { a } from "a"; + + +//// [user.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/tests/baselines/reference/typesVersions.justIndex.symbols b/tests/baselines/reference/typesVersions.justIndex.symbols new file mode 100644 index 00000000000..a4441e407d7 --- /dev/null +++ b/tests/baselines/reference/typesVersions.justIndex.symbols @@ -0,0 +1,8 @@ +=== /a/ts3.1/index.d.ts === +export const a = 0; +>a : Symbol(a, Decl(index.d.ts, 0, 12)) + +=== /b/user.ts === +import { a } from "a"; +>a : Symbol(a, Decl(user.ts, 0, 8)) + diff --git a/tests/baselines/reference/typesVersions.justIndex.trace.json b/tests/baselines/reference/typesVersions.justIndex.trace.json new file mode 100644 index 00000000000..d69aa51f72d --- /dev/null +++ b/tests/baselines/reference/typesVersions.justIndex.trace.json @@ -0,0 +1,28 @@ +[ + "======== Resolving module 'a' from '/b/user.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'a'.", + "Resolving module name 'a' relative to base url '/' - '/a'.", + "Loading module as file / folder, candidate module location '/a', target file type 'TypeScript'.", + "File '/a.ts' does not exist.", + "File '/a.tsx' does not exist.", + "File '/a.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' does not have a 'main' field.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at '/a/package.json'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' does not have a 'main' field.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File '/a/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location '/a/ts3.1/index', target file type 'TypeScript'.", + "File '/a/ts3.1/index.ts' does not exist.", + "File '/a/ts3.1/index.tsx' does not exist.", + "File '/a/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "======== Module name 'a' was successfully resolved to '/a/ts3.1/index.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersions.justIndex.types b/tests/baselines/reference/typesVersions.justIndex.types new file mode 100644 index 00000000000..578d4695e1c --- /dev/null +++ b/tests/baselines/reference/typesVersions.justIndex.types @@ -0,0 +1,9 @@ +=== /a/ts3.1/index.d.ts === +export const a = 0; +>a : 0 +>0 : 0 + +=== /b/user.ts === +import { a } from "a"; +>a : 0 + diff --git a/tests/baselines/reference/typesVersions.multiFile.js b/tests/baselines/reference/typesVersions.multiFile.js new file mode 100644 index 00000000000..cca708988c6 --- /dev/null +++ b/tests/baselines/reference/typesVersions.multiFile.js @@ -0,0 +1,39 @@ +//// [tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +//// [index.d.ts] +export const a = "default a"; + +//// [other.d.ts] +export const b = "default b"; + +//// [index.d.ts] +export const a = "ts3.1 a"; + +//// [other.d.ts] +export const b = "ts3.1 b"; + +//// [main.ts] +import { a } from "ext"; +import { b } from "ext/other"; + +const aa: "ts3.1 a" = a; +const bb: "ts3.1 b" = b; + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +const aa = ext_1.a; +const bb = other_1.b; diff --git a/tests/baselines/reference/typesVersions.multiFile.symbols b/tests/baselines/reference/typesVersions.multiFile.symbols new file mode 100644 index 00000000000..11ea8b7857a --- /dev/null +++ b/tests/baselines/reference/typesVersions.multiFile.symbols @@ -0,0 +1,31 @@ +=== tests/cases/conformance/moduleResolution/node_modules/ext/index.d.ts === +export const a = "default a"; +>a : Symbol(a, Decl(index.d.ts, 0, 12)) + +=== tests/cases/conformance/moduleResolution/node_modules/ext/other.d.ts === +export const b = "default b"; +>b : Symbol(b, Decl(other.d.ts, 0, 12)) + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts === +export const a = "ts3.1 a"; +>a : Symbol(a, Decl(index.d.ts, 0, 12)) + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts === +export const b = "ts3.1 b"; +>b : Symbol(b, Decl(other.d.ts, 0, 12)) + +=== tests/cases/conformance/moduleResolution/main.ts === +import { a } from "ext"; +>a : Symbol(a, Decl(main.ts, 0, 8)) + +import { b } from "ext/other"; +>b : Symbol(b, Decl(main.ts, 1, 8)) + +const aa: "ts3.1 a" = a; +>aa : Symbol(aa, Decl(main.ts, 3, 5)) +>a : Symbol(a, Decl(main.ts, 0, 8)) + +const bb: "ts3.1 b" = b; +>bb : Symbol(bb, Decl(main.ts, 4, 5)) +>b : Symbol(b, Decl(main.ts, 1, 8)) + diff --git a/tests/baselines/reference/typesVersions.multiFile.trace.json b/tests/baselines/reference/typesVersions.multiFile.trace.json new file mode 100644 index 00000000000..d52db48acfe --- /dev/null +++ b/tests/baselines/reference/typesVersions.multiFile.trace.json @@ -0,0 +1,37 @@ +[ + "======== Resolving module 'ext' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts'.", + "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersions.multiFile.types b/tests/baselines/reference/typesVersions.multiFile.types new file mode 100644 index 00000000000..734a90067cb --- /dev/null +++ b/tests/baselines/reference/typesVersions.multiFile.types @@ -0,0 +1,35 @@ +=== tests/cases/conformance/moduleResolution/node_modules/ext/index.d.ts === +export const a = "default a"; +>a : "default a" +>"default a" : "default a" + +=== tests/cases/conformance/moduleResolution/node_modules/ext/other.d.ts === +export const b = "default b"; +>b : "default b" +>"default b" : "default b" + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts === +export const a = "ts3.1 a"; +>a : "ts3.1 a" +>"ts3.1 a" : "ts3.1 a" + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts === +export const b = "ts3.1 b"; +>b : "ts3.1 b" +>"ts3.1 b" : "ts3.1 b" + +=== tests/cases/conformance/moduleResolution/main.ts === +import { a } from "ext"; +>a : "ts3.1 a" + +import { b } from "ext/other"; +>b : "ts3.1 b" + +const aa: "ts3.1 a" = a; +>aa : "ts3.1 a" +>a : "ts3.1 a" + +const bb: "ts3.1 b" = b; +>bb : "ts3.1 b" +>b : "ts3.1 b" + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js new file mode 100644 index 00000000000..ddd2f8b0ef5 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js @@ -0,0 +1,51 @@ +//// [tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +//// [index.d.ts] +declare module "ext" { + export interface A {} + export function fa(): A; +} +declare module "ext/other" { + export interface B {} + export function fb(): B; +} +//// [index.d.ts] +declare module "ext" { + export interface A {} + export function fa(): A; +} +declare module "ext/other" { + export interface B {} + export function fb(): B; +} + +//// [main.ts] +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +exports.va = ext_1.fa(); +exports.vb = other_1.fb(); + + +//// [main.d.ts] +export declare const va: import("ext").A; +export declare const vb: import("ext/other").B; diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols new file mode 100644 index 00000000000..2e4794ba56a --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols @@ -0,0 +1,37 @@ +=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +import { fb } from "ext/other"; +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + +export const va = fa(); +>va : Symbol(va, Decl(main.ts, 3, 12)) +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +export const vb = fb(); +>vb : Symbol(vb, Decl(main.ts, 4, 12)) +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +declare module "ext" { +>"ext" : Symbol("ext", Decl(index.d.ts, 0, 0)) + + export interface A {} +>A : Symbol(A, Decl(index.d.ts, 0, 22)) + + export function fa(): A; +>fa : Symbol(fa, Decl(index.d.ts, 1, 25)) +>A : Symbol(A, Decl(index.d.ts, 0, 22)) +} +declare module "ext/other" { +>"ext/other" : Symbol("ext/other", Decl(index.d.ts, 3, 1)) + + export interface B {} +>B : Symbol(B, Decl(index.d.ts, 4, 28)) + + export function fb(): B; +>fb : Symbol(fb, Decl(index.d.ts, 5, 25)) +>B : Symbol(B, Decl(index.d.ts, 4, 28)) +} + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json new file mode 100644 index 00000000000..2fcf9d052d4 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json @@ -0,0 +1,63 @@ +[ + "======== Resolving module 'ext' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts' does not exist.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other/ts3.1/index', target file type 'TypeScript'.", + "Directory 'tests/cases/conformance/declarationEmit/node_modules/@types' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/node_modules' does not exist, skipping all lookups in it.", + "Directory 'node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.js' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.jsx' does not exist.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other/ts3.1/index', target file type 'JavaScript'.", + "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/node_modules' does not exist, skipping all lookups in it.", + "Directory 'node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name 'ext/other' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types new file mode 100644 index 00000000000..3599ee312a3 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : () => import("ext").A + +import { fb } from "ext/other"; +>fb : () => import("ext/other").B + +export const va = fa(); +>va : import("ext").A +>fa() : import("ext").A +>fa : () => import("ext").A + +export const vb = fb(); +>vb : import("ext/other").B +>fb() : import("ext/other").B +>fb : () => import("ext/other").B + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +declare module "ext" { +>"ext" : typeof import("ext") + + export interface A {} + export function fa(): A; +>fa : () => A +} +declare module "ext/other" { +>"ext/other" : typeof import("ext/other") + + export interface B {} + export function fb(): B; +>fb : () => B +} + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js new file mode 100644 index 00000000000..5fd7da959ea --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js @@ -0,0 +1,48 @@ +//// [tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +//// [index.d.ts] +export interface A {} +export function fa(): A; + +//// [other.d.ts] +export interface B {} +export function fb(): B; + +//// [index.d.ts] +export interface A {} +export function fa(): A; + +//// [other.d.ts] +export interface B {} +export function fb(): B; + +//// [main.ts] +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +exports.va = ext_1.fa(); +exports.vb = other_1.fb(); + + +//// [main.d.ts] +export declare const va: import("ext").A; +export declare const vb: import("ext/other").B; diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols new file mode 100644 index 00000000000..4449de33ded --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols @@ -0,0 +1,47 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +export function fa(): A; +>fa : Symbol(fa, Decl(index.d.ts, 0, 21)) +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface B {} +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +export function fb(): B; +>fb : Symbol(fb, Decl(other.d.ts, 0, 21)) +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +export interface A {} +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +export function fa(): A; +>fa : Symbol(fa, Decl(index.d.ts, 0, 21)) +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts === +export interface B {} +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +export function fb(): B; +>fb : Symbol(fb, Decl(other.d.ts, 0, 21)) +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +import { fb } from "ext/other"; +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + +export const va = fa(); +>va : Symbol(va, Decl(main.ts, 3, 12)) +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +export const vb = fb(); +>vb : Symbol(vb, Decl(main.ts, 4, 12)) +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json new file mode 100644 index 00000000000..eee9622037b --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json @@ -0,0 +1,37 @@ +[ + "======== Resolving module 'ext' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts'.", + "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types new file mode 100644 index 00000000000..9f9dd015942 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types @@ -0,0 +1,37 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +export function fa(): A; +>fa : () => A + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface B {} +export function fb(): B; +>fb : () => B + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +export interface A {} +export function fa(): A; +>fa : () => A + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts === +export interface B {} +export function fb(): B; +>fb : () => B + +=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index").A + +import { fb } from "ext/other"; +>fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other").B + +export const va = fa(); +>va : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index").A +>fa() : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index").A +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index").A + +export const vb = fb(); +>vb : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other").B +>fb() : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other").B +>fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other").B + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt new file mode 100644 index 00000000000..a6373dbda56 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt @@ -0,0 +1,38 @@ +tests/cases/conformance/declarationEmit/main.ts(1,10): error TS2305: Module '"./node_modules/ext/ts3.1"' has no exported member 'fa'. + + +==== tests/cases/conformance/declarationEmit/tsconfig.json (0 errors) ==== + {} +==== tests/cases/conformance/declarationEmit/node_modules/ext/package.json (0 errors) ==== + { + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } + } + +==== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts (0 errors) ==== + export interface A {} + export function fa(): A; + +==== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts (0 errors) ==== + export interface B {} + export function fb(): B; + +==== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts (0 errors) ==== + export * from "../"; + +==== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts (0 errors) ==== + export * from "../other"; + +==== tests/cases/conformance/declarationEmit/main.ts (1 errors) ==== + import { fa } from "ext"; + ~~ +!!! error TS2305: Module '"./node_modules/ext/ts3.1"' has no exported member 'fa'. + import { fb } from "ext/other"; + + export const va = fa(); + export const vb = fb(); + \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js new file mode 100644 index 00000000000..ab415ca2b61 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js @@ -0,0 +1,46 @@ +//// [tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +//// [index.d.ts] +export interface A {} +export function fa(): A; + +//// [other.d.ts] +export interface B {} +export function fb(): B; + +//// [index.d.ts] +export * from "../"; + +//// [other.d.ts] +export * from "../other"; + +//// [main.ts] +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +exports.va = ext_1.fa(); +exports.vb = other_1.fb(); + + +//// [main.d.ts] +export declare const va: any; +export declare const vb: import("ext/other").B; diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.symbols b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.symbols new file mode 100644 index 00000000000..a3367579265 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.symbols @@ -0,0 +1,37 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +export function fa(): A; +>fa : Symbol(fa, Decl(index.d.ts, 0, 21)) +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface B {} +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +export function fb(): B; +>fb : Symbol(fb, Decl(other.d.ts, 0, 21)) +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +export * from "../"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts === +export * from "../other"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +import { fb } from "ext/other"; +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + +export const va = fa(); +>va : Symbol(va, Decl(main.ts, 3, 12)) +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +export const vb = fb(); +>vb : Symbol(vb, Decl(main.ts, 4, 12)) +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json new file mode 100644 index 00000000000..cf08a29478f --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json @@ -0,0 +1,65 @@ +[ + "======== Resolving module '../' from 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/', target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/ndex/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "======== Module name '../' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "======== Resolving module '../other' from 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/other', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts' exist - use it as a name resolution result.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other.d.ts@1.0.0'.", + "======== Module name '../other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts'. ========", + "======== Resolving module 'ext' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts'.", + "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.types b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.types new file mode 100644 index 00000000000..05800e1d35d --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +export function fa(): A; +>fa : () => A + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface B {} +export function fb(): B; +>fb : () => B + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +export * from "../"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts === +export * from "../other"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : any + +import { fb } from "ext/other"; +>fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").B + +export const va = fa(); +>va : any +>fa() : any +>fa : any + +export const vb = fb(); +>vb : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").B +>fb() : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").B +>fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").B + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js new file mode 100644 index 00000000000..fb7dfd74b2d --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js @@ -0,0 +1,45 @@ +//// [tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "index" : ["ts3.1/index"] + } + } +} + +//// [index.d.ts] +export interface A {} +export function fa(): A; + +//// [other.d.ts] +export interface A2 {} +export function fa(): A2; + +//// [index.d.ts] +export * from "../other"; + +//// [main.ts] +import { fa } from "ext"; +import { fa as fa2 } from "ext/other"; + +export const va = fa(); +export const va2 = fa2(); + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +exports.va = ext_1.fa(); +exports.va2 = other_1.fa(); + + +//// [main.d.ts] +export declare const va: import("ext/other").A2; +export declare const va2: import("ext/other").A2; diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.symbols b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.symbols new file mode 100644 index 00000000000..892e521994b --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.symbols @@ -0,0 +1,35 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +export function fa(): A; +>fa : Symbol(fa, Decl(index.d.ts, 0, 21)) +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface A2 {} +>A2 : Symbol(A2, Decl(other.d.ts, 0, 0)) + +export function fa(): A2; +>fa : Symbol(fa, Decl(other.d.ts, 0, 22)) +>A2 : Symbol(A2, Decl(other.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +export * from "../other"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +import { fa as fa2 } from "ext/other"; +>fa : Symbol(fa2, Decl(main.ts, 1, 8)) +>fa2 : Symbol(fa2, Decl(main.ts, 1, 8)) + +export const va = fa(); +>va : Symbol(va, Decl(main.ts, 3, 12)) +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +export const va2 = fa2(); +>va2 : Symbol(va2, Decl(main.ts, 4, 12)) +>fa2 : Symbol(fa2, Decl(main.ts, 1, 8)) + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json new file mode 100644 index 00000000000..fe65b605283 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json @@ -0,0 +1,44 @@ +[ + "======== Resolving module '../other' from 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/other', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts' exist - use it as a name resolution result.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other.d.ts@1.0.0'.", + "======== Module name '../other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts'. ========", + "======== Resolving module 'ext' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern 'index'.", + "Trying substitution 'ts3.1/index', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts'.", + "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.types b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.types new file mode 100644 index 00000000000..d2918314133 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.types @@ -0,0 +1,31 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +export function fa(): A; +>fa : () => A + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface A2 {} +export function fa(): A2; +>fa : () => A2 + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +export * from "../other"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 + +import { fa as fa2 } from "ext/other"; +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 +>fa2 : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 + +export const va = fa(); +>va : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 +>fa() : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 + +export const va2 = fa2(); +>va2 : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 +>fa2() : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 +>fa2 : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 + diff --git a/tests/baselines/reference/typesWithPublicConstructor.errors.txt b/tests/baselines/reference/typesWithPublicConstructor.errors.txt index d3b03740bf2..9aa44dea89d 100644 --- a/tests/baselines/reference/typesWithPublicConstructor.errors.txt +++ b/tests/baselines/reference/typesWithPublicConstructor.errors.txt @@ -24,4 +24,5 @@ tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): erro var c2 = new C2(); ~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/members/typesWithPublicConstructor.ts:11:24: An argument for 'x' was not provided. var r2: (x: number) => void = c2.constructor; \ No newline at end of file diff --git a/tests/baselines/reference/typesWithSpecializedCallSignatures.js b/tests/baselines/reference/typesWithSpecializedCallSignatures.js index b45cd7f9306..6cb2fbaff54 100644 --- a/tests/baselines/reference/typesWithSpecializedCallSignatures.js +++ b/tests/baselines/reference/typesWithSpecializedCallSignatures.js @@ -49,7 +49,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typesWithSpecializedConstructSignatures.js b/tests/baselines/reference/typesWithSpecializedConstructSignatures.js index 78fceafe3b0..7bbe983955d 100644 --- a/tests/baselines/reference/typesWithSpecializedConstructSignatures.js +++ b/tests/baselines/reference/typesWithSpecializedConstructSignatures.js @@ -47,7 +47,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/typingsLookup4.trace.json b/tests/baselines/reference/typingsLookup4.trace.json index 6cd025d099a..86b386670d6 100644 --- a/tests/baselines/reference/typingsLookup4.trace.json +++ b/tests/baselines/reference/typingsLookup4.trace.json @@ -6,6 +6,7 @@ "File '/node_modules/jquery.tsx' does not exist.", "File '/node_modules/jquery.d.ts' does not exist.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", "File '/node_modules/@types/jquery.d.ts' does not exist.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", @@ -19,6 +20,7 @@ "File '/node_modules/kquery.tsx' does not exist.", "File '/node_modules/kquery.d.ts' does not exist.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", "File '/node_modules/@types/kquery.d.ts' does not exist.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", @@ -36,6 +38,7 @@ "File '/node_modules/lquery.tsx' does not exist.", "File '/node_modules/lquery.d.ts' does not exist.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", "File '/node_modules/@types/lquery.d.ts' does not exist.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", @@ -51,6 +54,7 @@ "File '/node_modules/mquery.tsx' does not exist.", "File '/node_modules/mquery.d.ts' does not exist.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/mquery/package.json'.", "File '/node_modules/@types/mquery.d.ts' does not exist.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", @@ -66,7 +70,9 @@ "======== Resolving type reference directive 'jquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", "File '/node_modules/@types/jquery/jquery.d.ts' exist - use it as a name resolution result.", "Resolving real path for '/node_modules/@types/jquery/jquery.d.ts', result '/node_modules/@types/jquery/jquery.d.ts'.", @@ -74,7 +80,9 @@ "======== Resolving type reference directive 'kquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", "File '/node_modules/@types/kquery/kquery' does not exist.", "Loading module as file / folder, candidate module location '/node_modules/@types/kquery/kquery', target file type 'TypeScript'.", @@ -86,7 +94,9 @@ "======== Resolving type reference directive 'lquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", "File '/node_modules/@types/lquery/lquery' does not exist.", "Loading module as file / folder, candidate module location '/node_modules/@types/lquery/lquery', target file type 'TypeScript'.", @@ -96,7 +106,9 @@ "======== Resolving type reference directive 'mquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/mquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", "File '/node_modules/@types/mquery/mquery' does not exist.", "Loading module as file / folder, candidate module location '/node_modules/@types/mquery/mquery', target file type 'TypeScript'.", diff --git a/tests/baselines/reference/umd-augmentation-3.symbols b/tests/baselines/reference/umd-augmentation-3.symbols index 606c7cd2398..9ddd303bfc7 100644 --- a/tests/baselines/reference/umd-augmentation-3.symbols +++ b/tests/baselines/reference/umd-augmentation-3.symbols @@ -44,7 +44,7 @@ export = M2D; >M2D : Symbol(M2D, Decl(index.d.ts, 2, 13)) declare namespace M2D { ->M2D : Symbol(M2D, Decl(index.d.ts, 2, 13), Decl(math2d-augment.d.ts, 0, 33)) +>M2D : Symbol("tests/cases/conformance/externalModules/node_modules/math2d/index.d.ts", Decl(index.d.ts, 2, 13), Decl(math2d-augment.d.ts, 0, 33)) interface Point { >Point : Symbol(Point, Decl(index.d.ts, 4, 23)) diff --git a/tests/baselines/reference/umd-augmentation-4.symbols b/tests/baselines/reference/umd-augmentation-4.symbols index 90341d679f0..4a2e8090e9f 100644 --- a/tests/baselines/reference/umd-augmentation-4.symbols +++ b/tests/baselines/reference/umd-augmentation-4.symbols @@ -42,7 +42,7 @@ export = M2D; >M2D : Symbol(M2D, Decl(index.d.ts, 2, 13)) declare namespace M2D { ->M2D : Symbol(M2D, Decl(index.d.ts, 2, 13), Decl(math2d-augment.d.ts, 0, 33)) +>M2D : Symbol("tests/cases/conformance/externalModules/node_modules/math2d/index.d.ts", Decl(index.d.ts, 2, 13), Decl(math2d-augment.d.ts, 0, 33)) interface Point { >Point : Symbol(Point, Decl(index.d.ts, 4, 23)) diff --git a/tests/baselines/reference/unclosedExportClause01.errors.txt b/tests/baselines/reference/unclosedExportClause01.errors.txt index 9c6cae88ba1..4cc6363bb73 100644 --- a/tests/baselines/reference/unclosedExportClause01.errors.txt +++ b/tests/baselines/reference/unclosedExportClause01.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/t2.ts(1,13): error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +tests/cases/compiler/t2.ts(1,13): error TS2305: Module '"./t1"' has no exported member 'from'. tests/cases/compiler/t2.ts(1,18): error TS1005: ',' expected. -tests/cases/compiler/t3.ts(1,10): error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +tests/cases/compiler/t3.ts(1,10): error TS2305: Module '"./t1"' has no exported member 'from'. tests/cases/compiler/t3.ts(1,15): error TS1005: ',' expected. tests/cases/compiler/t4.ts(1,17): error TS1005: ',' expected. -tests/cases/compiler/t4.ts(1,17): error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +tests/cases/compiler/t4.ts(1,17): error TS2305: Module '"./t1"' has no exported member 'from'. tests/cases/compiler/t4.ts(1,22): error TS1005: ',' expected. -tests/cases/compiler/t5.ts(1,18): error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +tests/cases/compiler/t5.ts(1,18): error TS2305: Module '"./t1"' has no exported member 'from'. tests/cases/compiler/t5.ts(1,23): error TS1005: ',' expected. @@ -15,14 +15,14 @@ tests/cases/compiler/t5.ts(1,23): error TS1005: ',' expected. ==== tests/cases/compiler/t2.ts (2 errors) ==== export { x, from "./t1" ~~~~ -!!! error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +!!! error TS2305: Module '"./t1"' has no exported member 'from'. ~~~~~~ !!! error TS1005: ',' expected. ==== tests/cases/compiler/t3.ts (2 errors) ==== export { from "./t1" ~~~~ -!!! error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +!!! error TS2305: Module '"./t1"' has no exported member 'from'. ~~~~~~ !!! error TS1005: ',' expected. @@ -31,13 +31,13 @@ tests/cases/compiler/t5.ts(1,23): error TS1005: ',' expected. ~~~~ !!! error TS1005: ',' expected. ~~~~ -!!! error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +!!! error TS2305: Module '"./t1"' has no exported member 'from'. ~~~~~~ !!! error TS1005: ',' expected. ==== tests/cases/compiler/t5.ts (2 errors) ==== export { x as a, from "./t1" ~~~~ -!!! error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +!!! error TS2305: Module '"./t1"' has no exported member 'from'. ~~~~~~ !!! error TS1005: ',' expected. \ No newline at end of file diff --git a/tests/baselines/reference/undeclaredBase.js b/tests/baselines/reference/undeclaredBase.js index 8c48576d6af..efbd2b49b41 100644 --- a/tests/baselines/reference/undeclaredBase.js +++ b/tests/baselines/reference/undeclaredBase.js @@ -10,7 +10,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.errors.txt b/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.errors.txt new file mode 100644 index 00000000000..dec048bb87c --- /dev/null +++ b/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/undefinedAssignableToGenericMappedIntersection.ts(5,5): error TS2322: Type 'undefined' is not assignable to type 'Errors[keyof T]'. + + +==== tests/cases/compiler/undefinedAssignableToGenericMappedIntersection.ts (1 errors) ==== + type Errors = { [P in keyof T]: string | undefined } & {all: string | undefined}; + function foo() { + let obj!: Errors + let x!: keyof T; + obj[x] = undefined; + ~~~~~~ +!!! error TS2322: Type 'undefined' is not assignable to type 'Errors[keyof T]'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.js b/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.js new file mode 100644 index 00000000000..468344c3e9c --- /dev/null +++ b/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.js @@ -0,0 +1,16 @@ +//// [undefinedAssignableToGenericMappedIntersection.ts] +type Errors = { [P in keyof T]: string | undefined } & {all: string | undefined}; +function foo() { + let obj!: Errors + let x!: keyof T; + obj[x] = undefined; +} + + +//// [undefinedAssignableToGenericMappedIntersection.js] +"use strict"; +function foo() { + var obj; + var x; + obj[x] = undefined; +} diff --git a/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.symbols b/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.symbols new file mode 100644 index 00000000000..613b3bcc538 --- /dev/null +++ b/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.symbols @@ -0,0 +1,27 @@ +=== tests/cases/compiler/undefinedAssignableToGenericMappedIntersection.ts === +type Errors = { [P in keyof T]: string | undefined } & {all: string | undefined}; +>Errors : Symbol(Errors, Decl(undefinedAssignableToGenericMappedIntersection.ts, 0, 0)) +>T : Symbol(T, Decl(undefinedAssignableToGenericMappedIntersection.ts, 0, 12)) +>P : Symbol(P, Decl(undefinedAssignableToGenericMappedIntersection.ts, 0, 20)) +>T : Symbol(T, Decl(undefinedAssignableToGenericMappedIntersection.ts, 0, 12)) +>all : Symbol(all, Decl(undefinedAssignableToGenericMappedIntersection.ts, 0, 59)) + +function foo() { +>foo : Symbol(foo, Decl(undefinedAssignableToGenericMappedIntersection.ts, 0, 84)) +>T : Symbol(T, Decl(undefinedAssignableToGenericMappedIntersection.ts, 1, 13)) + + let obj!: Errors +>obj : Symbol(obj, Decl(undefinedAssignableToGenericMappedIntersection.ts, 2, 7)) +>Errors : Symbol(Errors, Decl(undefinedAssignableToGenericMappedIntersection.ts, 0, 0)) +>T : Symbol(T, Decl(undefinedAssignableToGenericMappedIntersection.ts, 1, 13)) + + let x!: keyof T; +>x : Symbol(x, Decl(undefinedAssignableToGenericMappedIntersection.ts, 3, 7)) +>T : Symbol(T, Decl(undefinedAssignableToGenericMappedIntersection.ts, 1, 13)) + + obj[x] = undefined; +>obj : Symbol(obj, Decl(undefinedAssignableToGenericMappedIntersection.ts, 2, 7)) +>x : Symbol(x, Decl(undefinedAssignableToGenericMappedIntersection.ts, 3, 7)) +>undefined : Symbol(undefined) +} + diff --git a/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.types b/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.types new file mode 100644 index 00000000000..1bf4aae0198 --- /dev/null +++ b/tests/baselines/reference/undefinedAssignableToGenericMappedIntersection.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/undefinedAssignableToGenericMappedIntersection.ts === +type Errors = { [P in keyof T]: string | undefined } & {all: string | undefined}; +>Errors : Errors +>all : string | undefined + +function foo() { +>foo : () => void + + let obj!: Errors +>obj : Errors + + let x!: keyof T; +>x : keyof T + + obj[x] = undefined; +>obj[x] = undefined : undefined +>obj[x] : Errors[keyof T] +>obj : Errors +>x : keyof T +>undefined : undefined +} + diff --git a/tests/baselines/reference/undefinedIsSubtypeOfEverything.js b/tests/baselines/reference/undefinedIsSubtypeOfEverything.js index c2a2647814e..40378779e0c 100644 --- a/tests/baselines/reference/undefinedIsSubtypeOfEverything.js +++ b/tests/baselines/reference/undefinedIsSubtypeOfEverything.js @@ -129,7 +129,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/underscoreMapFirst.js b/tests/baselines/reference/underscoreMapFirst.js index 721b82e61eb..4fc0d0bf3ce 100644 --- a/tests/baselines/reference/underscoreMapFirst.js +++ b/tests/baselines/reference/underscoreMapFirst.js @@ -55,7 +55,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/underscoreThisInDerivedClass01.js b/tests/baselines/reference/underscoreThisInDerivedClass01.js index de498b144f1..c42767ef3bf 100644 --- a/tests/baselines/reference/underscoreThisInDerivedClass01.js +++ b/tests/baselines/reference/underscoreThisInDerivedClass01.js @@ -31,7 +31,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/underscoreThisInDerivedClass02.js b/tests/baselines/reference/underscoreThisInDerivedClass02.js index ea15dbe5fd1..313b6663d54 100644 --- a/tests/baselines/reference/underscoreThisInDerivedClass02.js +++ b/tests/baselines/reference/underscoreThisInDerivedClass02.js @@ -26,7 +26,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/unionTypeCallSignatures.errors.txt b/tests/baselines/reference/unionTypeCallSignatures.errors.txt index c123dc8da56..3f0ac662013 100644 --- a/tests/baselines/reference/unionTypeCallSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures.errors.txt @@ -56,6 +56,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 unionOfDifferentReturnType1(); // error missing parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:12:37: An argument for 'a' was not provided. var unionOfDifferentParameterTypes: { (a: number): number; } | { (a: string): Date; }; unionOfDifferentParameterTypes(10);// error - no call signatures @@ -72,6 +73,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 unionOfDifferentNumberOfSignatures(); // error - no call signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:23:44: An argument for 'a' was not provided. unionOfDifferentNumberOfSignatures(10); // error - no call signatures unionOfDifferentNumberOfSignatures("hello"); // error - no call signatures ~~~~~~~ @@ -97,11 +99,13 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithOptionalParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:33:37: An argument for 'a' was not provided. var unionWithOptionalParameter2: { (a: string, b?: number): string; } | { (a: string, b: number): number }; strOrNum = unionWithOptionalParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:39:87: An argument for 'b' was not provided. strOrNum = unionWithOptionalParameter2('hello', 10); // error no call signature strOrNum = unionWithOptionalParameter2('hello', "hello"); // error no call signature ~~~~~~~ @@ -109,6 +113,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithOptionalParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:39:76: An argument for 'a' was not provided. var unionWithOptionalParameter3: { (a: string, b?: number): string; } | { (a: string): number; }; strOrNum = unionWithOptionalParameter3('hello'); @@ -121,6 +126,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithOptionalParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:45:76: An argument for 'a' was not provided. var unionWithRestParameter1: { (a: string, ...b: number[]): string; } | { (a: string, ...b: number[]): number }; strOrNum = unionWithRestParameter1('hello'); @@ -132,11 +138,13 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2555: Expected at least 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:51:33: An argument for 'a' was not provided. var unionWithRestParameter2: { (a: string, ...b: number[]): string; } | { (a: string, b: number): number }; strOrNum = unionWithRestParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:58:87: An argument for 'b' was not provided. strOrNum = unionWithRestParameter2('hello', 10); // error no call signature strOrNum = unionWithRestParameter2('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -147,6 +155,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithRestParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:58:76: An argument for 'a' was not provided. var unionWithRestParameter3: { (a: string, ...b: number[]): string; } | { (a: string): number }; strOrNum = unionWithRestParameter3('hello'); @@ -162,10 +171,12 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithRestParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:65:76: An argument for 'a' was not provided. var unionWithRestParameter4: { (...a: string[]): string; } | { (a: string, b: string): number; }; strOrNum = unionWithRestParameter4("hello"); // error supplied parameters do not match any call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:72:76: An argument for 'b' was not provided. strOrNum = unionWithRestParameter4("hello", "world"); \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures4.errors.txt b/tests/baselines/reference/unionTypeCallSignatures4.errors.txt index 1d9c3d272f0..9d2ca23bbbd 100644 --- a/tests/baselines/reference/unionTypeCallSignatures4.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures4.errors.txt @@ -34,6 +34,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2 f12345("a"); // error ~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures4.ts:5:23: An argument for 'b' was not provided. f12345("a", "b"); f12345("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt index 8b4c6f9aa0c..67973c3c206 100644 --- a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt @@ -55,6 +55,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro new unionOfDifferentReturnType1(); // error missing parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:12:41: An argument for 'a' was not provided. var unionOfDifferentParameterTypes: { new (a: number): number; } | { new (a: string): Date; }; new unionOfDifferentParameterTypes(10);// error - no call signatures @@ -71,6 +72,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro new unionOfDifferentNumberOfSignatures(); // error - no call signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:23:48: An argument for 'a' was not provided. new unionOfDifferentNumberOfSignatures(10); // error - no call signatures new unionOfDifferentNumberOfSignatures("hello"); // error - no call signatures ~~~~~~~ @@ -96,11 +98,13 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro strOrNum = new unionWithOptionalParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:33:41: An argument for 'a' was not provided. var unionWithOptionalParameter2: { new (a: string, b?: number): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithOptionalParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:39:95: An argument for 'b' was not provided. strOrNum = new unionWithOptionalParameter2('hello', 10); // error no call signature strOrNum = new unionWithOptionalParameter2('hello', "hello"); // error no call signature ~~~~~~~ @@ -108,6 +112,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro strOrNum = new unionWithOptionalParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:39:84: An argument for 'a' was not provided. var unionWithOptionalParameter3: { new (a: string, b?: number): string; } | { new (a: string): number; }; strOrNum = new unionWithOptionalParameter3('hello'); // error no call signature @@ -120,6 +125,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro strOrNum = new unionWithOptionalParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:45:84: An argument for 'a' was not provided. var unionWithRestParameter1: { new (a: string, ...b: number[]): string; } | { new (a: string, ...b: number[]): number }; strOrNum = new unionWithRestParameter1('hello'); @@ -131,11 +137,13 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro strOrNum = new unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2555: Expected at least 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:51:37: An argument for 'a' was not provided. var unionWithRestParameter2: { new (a: string, ...b: number[]): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithRestParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:58:95: An argument for 'b' was not provided. strOrNum = new unionWithRestParameter2('hello', 10); // error no call signature strOrNum = new unionWithRestParameter2('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -146,6 +154,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro strOrNum = new unionWithRestParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:58:84: An argument for 'a' was not provided. var unionWithRestParameter3: { new (a: string, ...b: number[]): string; } | { new (a: string): number }; strOrNum = new unionWithRestParameter3('hello'); // error no call signature @@ -160,4 +169,5 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2554: Expected 1 arguments, but got 2. strOrNum = new unionWithRestParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:65:84: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeEquivalence.js b/tests/baselines/reference/unionTypeEquivalence.js index 97a82c5ba0a..90ebc0ff152 100644 --- a/tests/baselines/reference/unionTypeEquivalence.js +++ b/tests/baselines/reference/unionTypeEquivalence.js @@ -26,7 +26,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/unionTypeFromArrayLiteral.js b/tests/baselines/reference/unionTypeFromArrayLiteral.js index 2a7791abaea..3c8e461ef18 100644 --- a/tests/baselines/reference/unionTypeFromArrayLiteral.js +++ b/tests/baselines/reference/unionTypeFromArrayLiteral.js @@ -34,7 +34,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.js b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.js new file mode 100644 index 00000000000..c78435ef0ce --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.js @@ -0,0 +1,15 @@ +//// [unionTypeWithIndexAndMethodSignature.ts] +interface Options { + m(x: number): void; + [key: string]: unknown; +} +declare function f(options: number | Options): void; +f({ + m(x) { }, +}); + +//// [unionTypeWithIndexAndMethodSignature.js] +"use strict"; +f({ + m: function (x) { } +}); diff --git a/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.symbols b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.symbols new file mode 100644 index 00000000000..3eaae1f320d --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.symbols @@ -0,0 +1,24 @@ +=== tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts === +interface Options { +>Options : Symbol(Options, Decl(unionTypeWithIndexAndMethodSignature.ts, 0, 0)) + + m(x: number): void; +>m : Symbol(Options.m, Decl(unionTypeWithIndexAndMethodSignature.ts, 0, 19)) +>x : Symbol(x, Decl(unionTypeWithIndexAndMethodSignature.ts, 1, 6)) + + [key: string]: unknown; +>key : Symbol(key, Decl(unionTypeWithIndexAndMethodSignature.ts, 2, 5)) +} +declare function f(options: number | Options): void; +>f : Symbol(f, Decl(unionTypeWithIndexAndMethodSignature.ts, 3, 1)) +>options : Symbol(options, Decl(unionTypeWithIndexAndMethodSignature.ts, 4, 19)) +>Options : Symbol(Options, Decl(unionTypeWithIndexAndMethodSignature.ts, 0, 0)) + +f({ +>f : Symbol(f, Decl(unionTypeWithIndexAndMethodSignature.ts, 3, 1)) + + m(x) { }, +>m : Symbol(m, Decl(unionTypeWithIndexAndMethodSignature.ts, 5, 3)) +>x : Symbol(x, Decl(unionTypeWithIndexAndMethodSignature.ts, 6, 6)) + +}); diff --git a/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.types b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.types new file mode 100644 index 00000000000..76607a40167 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.types @@ -0,0 +1,23 @@ +=== tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts === +interface Options { + m(x: number): void; +>m : (x: number) => void +>x : number + + [key: string]: unknown; +>key : string +} +declare function f(options: number | Options): void; +>f : (options: number | Options) => void +>options : number | Options + +f({ +>f({ m(x) { },}) : void +>f : (options: number | Options) => void +>{ m(x) { },} : { m(x: number): void; } + + m(x) { }, +>m : (x: number) => void +>x : number + +}); diff --git a/tests/baselines/reference/unionTypeWithIndexSignature.errors.txt b/tests/baselines/reference/unionTypeWithIndexSignature.errors.txt index 7f4675b0373..e95a184d15a 100644 --- a/tests/baselines/reference/unionTypeWithIndexSignature.errors.txt +++ b/tests/baselines/reference/unionTypeWithIndexSignature.errors.txt @@ -1,13 +1,12 @@ tests/cases/conformance/types/union/unionTypeWithIndexSignature.ts(11,3): error TS2339: Property 'bar' does not exist on type 'Missing'. Property 'bar' does not exist on type '{ [s: string]: string; }'. tests/cases/conformance/types/union/unionTypeWithIndexSignature.ts(14,4): error TS2540: Cannot assign to 'foo' because it is a constant or a read-only property. -tests/cases/conformance/types/union/unionTypeWithIndexSignature.ts(18,1): error TS2322: Type '"ok"' is not assignable to type 'number'. tests/cases/conformance/types/union/unionTypeWithIndexSignature.ts(24,1): error TS7017: Element implicitly has an 'any' type because type 'Both' has no index signature. tests/cases/conformance/types/union/unionTypeWithIndexSignature.ts(25,1): error TS2322: Type '"not ok"' is not assignable to type 'number'. tests/cases/conformance/types/union/unionTypeWithIndexSignature.ts(26,1): error TS7017: Element implicitly has an 'any' type because type 'Both' has no index signature. -==== tests/cases/conformance/types/union/unionTypeWithIndexSignature.ts (6 errors) ==== +==== tests/cases/conformance/types/union/unionTypeWithIndexSignature.ts (5 errors) ==== type Two = { foo: { bar: true }, baz: true } | { [s: string]: string }; declare var u: Two u.foo = 'bye' @@ -31,8 +30,6 @@ tests/cases/conformance/types/union/unionTypeWithIndexSignature.ts(26,1): error declare var num: Num num[0] = 1 num['0'] = 'ok' - ~~~~~~~~ -!!! error TS2322: Type '"ok"' is not assignable to type 'number'. const sym = Symbol() type Both = { s: number, '0': number, [sym]: boolean } | { [n: number]: number, [s: string]: string | number } declare var both: Both diff --git a/tests/baselines/reference/unionTypeWithIndexSignature.types b/tests/baselines/reference/unionTypeWithIndexSignature.types index a699d51391c..417d62e706e 100644 --- a/tests/baselines/reference/unionTypeWithIndexSignature.types +++ b/tests/baselines/reference/unionTypeWithIndexSignature.types @@ -96,7 +96,7 @@ num[0] = 1 num['0'] = 'ok' >num['0'] = 'ok' : "ok" ->num['0'] : number +>num['0'] : string | number >num : Num >'0' : "0" >'ok' : "ok" diff --git a/tests/baselines/reference/unionTypeWithIndexedLiteralType.js b/tests/baselines/reference/unionTypeWithIndexedLiteralType.js new file mode 100644 index 00000000000..8ed8d32b3f5 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexedLiteralType.js @@ -0,0 +1,8 @@ +//// [unionTypeWithIndexedLiteralType.ts] +interface I { x: number; } +interface Idx { [index: string]: U; } +type U = Idx | I | "lit"; +const u: U = { x: "lit" }; + +//// [unionTypeWithIndexedLiteralType.js] +var u = { x: "lit" }; diff --git a/tests/baselines/reference/unionTypeWithIndexedLiteralType.symbols b/tests/baselines/reference/unionTypeWithIndexedLiteralType.symbols new file mode 100644 index 00000000000..bf9502ee5a5 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexedLiteralType.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/unionTypeWithIndexedLiteralType.ts === +interface I { x: number; } +>I : Symbol(I, Decl(unionTypeWithIndexedLiteralType.ts, 0, 0)) +>x : Symbol(I.x, Decl(unionTypeWithIndexedLiteralType.ts, 0, 13)) + +interface Idx { [index: string]: U; } +>Idx : Symbol(Idx, Decl(unionTypeWithIndexedLiteralType.ts, 0, 26)) +>index : Symbol(index, Decl(unionTypeWithIndexedLiteralType.ts, 1, 17)) +>U : Symbol(U, Decl(unionTypeWithIndexedLiteralType.ts, 1, 37)) + +type U = Idx | I | "lit"; +>U : Symbol(U, Decl(unionTypeWithIndexedLiteralType.ts, 1, 37)) +>Idx : Symbol(Idx, Decl(unionTypeWithIndexedLiteralType.ts, 0, 26)) +>I : Symbol(I, Decl(unionTypeWithIndexedLiteralType.ts, 0, 0)) + +const u: U = { x: "lit" }; +>u : Symbol(u, Decl(unionTypeWithIndexedLiteralType.ts, 3, 5)) +>U : Symbol(U, Decl(unionTypeWithIndexedLiteralType.ts, 1, 37)) +>x : Symbol(x, Decl(unionTypeWithIndexedLiteralType.ts, 3, 14)) + diff --git a/tests/baselines/reference/unionTypeWithIndexedLiteralType.types b/tests/baselines/reference/unionTypeWithIndexedLiteralType.types new file mode 100644 index 00000000000..47d1d6832e1 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexedLiteralType.types @@ -0,0 +1,16 @@ +=== tests/cases/compiler/unionTypeWithIndexedLiteralType.ts === +interface I { x: number; } +>x : number + +interface Idx { [index: string]: U; } +>index : string + +type U = Idx | I | "lit"; +>U : U + +const u: U = { x: "lit" }; +>u : U +>{ x: "lit" } : { x: "lit"; } +>x : "lit" +>"lit" : "lit" + diff --git a/tests/baselines/reference/unionTypesAssignability.js b/tests/baselines/reference/unionTypesAssignability.js index eadf45aa94a..fc7b0c5020f 100644 --- a/tests/baselines/reference/unionTypesAssignability.js +++ b/tests/baselines/reference/unionTypesAssignability.js @@ -80,7 +80,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/unionsOfTupleTypes1.errors.txt b/tests/baselines/reference/unionsOfTupleTypes1.errors.txt new file mode 100644 index 00000000000..d9cad5f1b11 --- /dev/null +++ b/tests/baselines/reference/unionsOfTupleTypes1.errors.txt @@ -0,0 +1,90 @@ +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(8,15): error TS2339: Property '2' does not exist on type '[string, number]'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(13,15): error TS2339: Property '2' does not exist on type 'T2'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(27,20): error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(28,20): error TS2460: Type 'T2' has no property '2'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(31,16): error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(32,16): error TS2460: Type 'T2' has no property '2'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(37,18): error TS2339: Property '2' does not exist on type '[string, number]'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(41,18): error TS2339: Property '2' does not exist on type 'T2'. + + +==== tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts (8 errors) ==== + type T1 = [string, number]; + type T2 = [boolean] | [string, number]; + type T3 = [string, ...number[]]; + type T4 = [boolean] | [string, ...number[]]; + + type T10 = T1[0]; // string + type T11 = T1[1]; // number + type T12 = T1[2]; // undefined + ~ +!!! error TS2339: Property '2' does not exist on type '[string, number]'. + type T1N = T1[number]; // string | number + + type T20 = T2[0]; // string | boolean + type T21 = T2[1]; // number | undefined + type T22 = T2[2]; // undefined + ~ +!!! error TS2339: Property '2' does not exist on type 'T2'. + type T2N = T2[number]; // string | number | boolean + + type T30 = T3[0]; // string + type T31 = T3[1]; // number + type T32 = T3[2]; // number + type T3N = T3[number]; // string | number + + type T40 = T4[0]; // string | boolean + type T41 = T4[1]; // number | undefined + type T42 = T4[2]; // number | undefined + type T4N = T4[number]; // string | number | boolean + + function f1(t1: T1, t2: T2, t3: T3, t4: T4, x: number) { + let [d10, d11, d12] = t1; // string, number + ~~~ +!!! error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'. + let [d20, d21, d22] = t2; // string | boolean, number | undefined + ~~~ +!!! error TS2460: Type 'T2' has no property '2'. + let [d30, d31, d32] = t3; // string, number, number + let [d40, d41, d42] = t4; // string | boolean, number | undefined, number | undefined + [d10, d11, d12] = t1; + ~~~ +!!! error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'. + [d20, d21, d22] = t2; + ~~~ +!!! error TS2460: Type 'T2' has no property '2'. + [d30, d31, d32] = t3; + [d40, d41, d42] = t4; + let t10 = t1[0]; // string + let t11 = t1[1]; // number + let t12 = t1[2]; // undefined + ~ +!!! error TS2339: Property '2' does not exist on type '[string, number]'. + let t1x = t1[x]; // string | number + let t20 = t2[0]; // string | boolean + let t21 = t2[1]; // number | undefined + let t22 = t2[2]; // undefined + ~ +!!! error TS2339: Property '2' does not exist on type 'T2'. + let t2x = t2[x]; // string | number | boolean + let t30 = t3[0]; // string + let t31 = t3[1]; // number + let t32 = t3[2]; // number + let t3x = t3[x]; // string | number + let t40 = t4[0]; // string | boolean + let t41 = t4[1]; // number | undefined + let t42 = t4[2]; // number | undefined + let t4x = t4[x]; // string | number | boolean + t1[1] = 42; + t2[1] = 42; + t3[1] = 42; + t4[1] = 42; + } + + // Repro from #27543 + + type Unioned = [string] | [string, number]; + const ex: Unioned = ["hi"] as Unioned; + + const [x, y] = ex; + \ No newline at end of file diff --git a/tests/baselines/reference/unionsOfTupleTypes1.js b/tests/baselines/reference/unionsOfTupleTypes1.js new file mode 100644 index 00000000000..de21e1153d0 --- /dev/null +++ b/tests/baselines/reference/unionsOfTupleTypes1.js @@ -0,0 +1,99 @@ +//// [unionsOfTupleTypes1.ts] +type T1 = [string, number]; +type T2 = [boolean] | [string, number]; +type T3 = [string, ...number[]]; +type T4 = [boolean] | [string, ...number[]]; + +type T10 = T1[0]; // string +type T11 = T1[1]; // number +type T12 = T1[2]; // undefined +type T1N = T1[number]; // string | number + +type T20 = T2[0]; // string | boolean +type T21 = T2[1]; // number | undefined +type T22 = T2[2]; // undefined +type T2N = T2[number]; // string | number | boolean + +type T30 = T3[0]; // string +type T31 = T3[1]; // number +type T32 = T3[2]; // number +type T3N = T3[number]; // string | number + +type T40 = T4[0]; // string | boolean +type T41 = T4[1]; // number | undefined +type T42 = T4[2]; // number | undefined +type T4N = T4[number]; // string | number | boolean + +function f1(t1: T1, t2: T2, t3: T3, t4: T4, x: number) { + let [d10, d11, d12] = t1; // string, number + let [d20, d21, d22] = t2; // string | boolean, number | undefined + let [d30, d31, d32] = t3; // string, number, number + let [d40, d41, d42] = t4; // string | boolean, number | undefined, number | undefined + [d10, d11, d12] = t1; + [d20, d21, d22] = t2; + [d30, d31, d32] = t3; + [d40, d41, d42] = t4; + let t10 = t1[0]; // string + let t11 = t1[1]; // number + let t12 = t1[2]; // undefined + let t1x = t1[x]; // string | number + let t20 = t2[0]; // string | boolean + let t21 = t2[1]; // number | undefined + let t22 = t2[2]; // undefined + let t2x = t2[x]; // string | number | boolean + let t30 = t3[0]; // string + let t31 = t3[1]; // number + let t32 = t3[2]; // number + let t3x = t3[x]; // string | number + let t40 = t4[0]; // string | boolean + let t41 = t4[1]; // number | undefined + let t42 = t4[2]; // number | undefined + let t4x = t4[x]; // string | number | boolean + t1[1] = 42; + t2[1] = 42; + t3[1] = 42; + t4[1] = 42; +} + +// Repro from #27543 + +type Unioned = [string] | [string, number]; +const ex: Unioned = ["hi"] as Unioned; + +const [x, y] = ex; + + +//// [unionsOfTupleTypes1.js] +"use strict"; +function f1(t1, t2, t3, t4, x) { + var d10 = t1[0], d11 = t1[1], d12 = t1[2]; // string, number + var d20 = t2[0], d21 = t2[1], d22 = t2[2]; // string | boolean, number | undefined + var d30 = t3[0], d31 = t3[1], d32 = t3[2]; // string, number, number + var d40 = t4[0], d41 = t4[1], d42 = t4[2]; // string | boolean, number | undefined, number | undefined + d10 = t1[0], d11 = t1[1], d12 = t1[2]; + d20 = t2[0], d21 = t2[1], d22 = t2[2]; + d30 = t3[0], d31 = t3[1], d32 = t3[2]; + d40 = t4[0], d41 = t4[1], d42 = t4[2]; + var t10 = t1[0]; // string + var t11 = t1[1]; // number + var t12 = t1[2]; // undefined + var t1x = t1[x]; // string | number + var t20 = t2[0]; // string | boolean + var t21 = t2[1]; // number | undefined + var t22 = t2[2]; // undefined + var t2x = t2[x]; // string | number | boolean + var t30 = t3[0]; // string + var t31 = t3[1]; // number + var t32 = t3[2]; // number + var t3x = t3[x]; // string | number + var t40 = t4[0]; // string | boolean + var t41 = t4[1]; // number | undefined + var t42 = t4[2]; // number | undefined + var t4x = t4[x]; // string | number | boolean + t1[1] = 42; + t2[1] = 42; + t3[1] = 42; + t4[1] = 42; +} +var ex = ["hi"]; +var x = ex[0], y = ex[1]; diff --git a/tests/baselines/reference/unionsOfTupleTypes1.symbols b/tests/baselines/reference/unionsOfTupleTypes1.symbols new file mode 100644 index 00000000000..8d9b9185e54 --- /dev/null +++ b/tests/baselines/reference/unionsOfTupleTypes1.symbols @@ -0,0 +1,241 @@ +=== tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts === +type T1 = [string, number]; +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) + +type T2 = [boolean] | [string, number]; +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) + +type T3 = [string, ...number[]]; +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) + +type T4 = [boolean] | [string, ...number[]]; +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) + +type T10 = T1[0]; // string +>T10 : Symbol(T10, Decl(unionsOfTupleTypes1.ts, 3, 44)) +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) + +type T11 = T1[1]; // number +>T11 : Symbol(T11, Decl(unionsOfTupleTypes1.ts, 5, 17)) +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) + +type T12 = T1[2]; // undefined +>T12 : Symbol(T12, Decl(unionsOfTupleTypes1.ts, 6, 17)) +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) + +type T1N = T1[number]; // string | number +>T1N : Symbol(T1N, Decl(unionsOfTupleTypes1.ts, 7, 17)) +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) + +type T20 = T2[0]; // string | boolean +>T20 : Symbol(T20, Decl(unionsOfTupleTypes1.ts, 8, 22)) +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) + +type T21 = T2[1]; // number | undefined +>T21 : Symbol(T21, Decl(unionsOfTupleTypes1.ts, 10, 17)) +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) + +type T22 = T2[2]; // undefined +>T22 : Symbol(T22, Decl(unionsOfTupleTypes1.ts, 11, 17)) +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) + +type T2N = T2[number]; // string | number | boolean +>T2N : Symbol(T2N, Decl(unionsOfTupleTypes1.ts, 12, 17)) +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) + +type T30 = T3[0]; // string +>T30 : Symbol(T30, Decl(unionsOfTupleTypes1.ts, 13, 22)) +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) + +type T31 = T3[1]; // number +>T31 : Symbol(T31, Decl(unionsOfTupleTypes1.ts, 15, 17)) +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) + +type T32 = T3[2]; // number +>T32 : Symbol(T32, Decl(unionsOfTupleTypes1.ts, 16, 17)) +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) + +type T3N = T3[number]; // string | number +>T3N : Symbol(T3N, Decl(unionsOfTupleTypes1.ts, 17, 17)) +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) + +type T40 = T4[0]; // string | boolean +>T40 : Symbol(T40, Decl(unionsOfTupleTypes1.ts, 18, 22)) +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) + +type T41 = T4[1]; // number | undefined +>T41 : Symbol(T41, Decl(unionsOfTupleTypes1.ts, 20, 17)) +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) + +type T42 = T4[2]; // number | undefined +>T42 : Symbol(T42, Decl(unionsOfTupleTypes1.ts, 21, 17)) +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) + +type T4N = T4[number]; // string | number | boolean +>T4N : Symbol(T4N, Decl(unionsOfTupleTypes1.ts, 22, 17)) +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) + +function f1(t1: T1, t2: T2, t3: T3, t4: T4, x: number) { +>f1 : Symbol(f1, Decl(unionsOfTupleTypes1.ts, 23, 22)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 25, 43)) + + let [d10, d11, d12] = t1; // string, number +>d10 : Symbol(d10, Decl(unionsOfTupleTypes1.ts, 26, 9)) +>d11 : Symbol(d11, Decl(unionsOfTupleTypes1.ts, 26, 13)) +>d12 : Symbol(d12, Decl(unionsOfTupleTypes1.ts, 26, 18)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) + + let [d20, d21, d22] = t2; // string | boolean, number | undefined +>d20 : Symbol(d20, Decl(unionsOfTupleTypes1.ts, 27, 9)) +>d21 : Symbol(d21, Decl(unionsOfTupleTypes1.ts, 27, 13)) +>d22 : Symbol(d22, Decl(unionsOfTupleTypes1.ts, 27, 18)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) + + let [d30, d31, d32] = t3; // string, number, number +>d30 : Symbol(d30, Decl(unionsOfTupleTypes1.ts, 28, 9)) +>d31 : Symbol(d31, Decl(unionsOfTupleTypes1.ts, 28, 13)) +>d32 : Symbol(d32, Decl(unionsOfTupleTypes1.ts, 28, 18)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) + + let [d40, d41, d42] = t4; // string | boolean, number | undefined, number | undefined +>d40 : Symbol(d40, Decl(unionsOfTupleTypes1.ts, 29, 9)) +>d41 : Symbol(d41, Decl(unionsOfTupleTypes1.ts, 29, 13)) +>d42 : Symbol(d42, Decl(unionsOfTupleTypes1.ts, 29, 18)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) + + [d10, d11, d12] = t1; +>d10 : Symbol(d10, Decl(unionsOfTupleTypes1.ts, 26, 9)) +>d11 : Symbol(d11, Decl(unionsOfTupleTypes1.ts, 26, 13)) +>d12 : Symbol(d12, Decl(unionsOfTupleTypes1.ts, 26, 18)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) + + [d20, d21, d22] = t2; +>d20 : Symbol(d20, Decl(unionsOfTupleTypes1.ts, 27, 9)) +>d21 : Symbol(d21, Decl(unionsOfTupleTypes1.ts, 27, 13)) +>d22 : Symbol(d22, Decl(unionsOfTupleTypes1.ts, 27, 18)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) + + [d30, d31, d32] = t3; +>d30 : Symbol(d30, Decl(unionsOfTupleTypes1.ts, 28, 9)) +>d31 : Symbol(d31, Decl(unionsOfTupleTypes1.ts, 28, 13)) +>d32 : Symbol(d32, Decl(unionsOfTupleTypes1.ts, 28, 18)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) + + [d40, d41, d42] = t4; +>d40 : Symbol(d40, Decl(unionsOfTupleTypes1.ts, 29, 9)) +>d41 : Symbol(d41, Decl(unionsOfTupleTypes1.ts, 29, 13)) +>d42 : Symbol(d42, Decl(unionsOfTupleTypes1.ts, 29, 18)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) + + let t10 = t1[0]; // string +>t10 : Symbol(t10, Decl(unionsOfTupleTypes1.ts, 34, 7)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) +>0 : Symbol(0) + + let t11 = t1[1]; // number +>t11 : Symbol(t11, Decl(unionsOfTupleTypes1.ts, 35, 7)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) +>1 : Symbol(1) + + let t12 = t1[2]; // undefined +>t12 : Symbol(t12, Decl(unionsOfTupleTypes1.ts, 36, 7)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) + + let t1x = t1[x]; // string | number +>t1x : Symbol(t1x, Decl(unionsOfTupleTypes1.ts, 37, 7)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 25, 43)) + + let t20 = t2[0]; // string | boolean +>t20 : Symbol(t20, Decl(unionsOfTupleTypes1.ts, 38, 7)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) +>0 : Symbol(0) + + let t21 = t2[1]; // number | undefined +>t21 : Symbol(t21, Decl(unionsOfTupleTypes1.ts, 39, 7)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) +>1 : Symbol(1) + + let t22 = t2[2]; // undefined +>t22 : Symbol(t22, Decl(unionsOfTupleTypes1.ts, 40, 7)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) + + let t2x = t2[x]; // string | number | boolean +>t2x : Symbol(t2x, Decl(unionsOfTupleTypes1.ts, 41, 7)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 25, 43)) + + let t30 = t3[0]; // string +>t30 : Symbol(t30, Decl(unionsOfTupleTypes1.ts, 42, 7)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) +>0 : Symbol(0) + + let t31 = t3[1]; // number +>t31 : Symbol(t31, Decl(unionsOfTupleTypes1.ts, 43, 7)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) + + let t32 = t3[2]; // number +>t32 : Symbol(t32, Decl(unionsOfTupleTypes1.ts, 44, 7)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) + + let t3x = t3[x]; // string | number +>t3x : Symbol(t3x, Decl(unionsOfTupleTypes1.ts, 45, 7)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 25, 43)) + + let t40 = t4[0]; // string | boolean +>t40 : Symbol(t40, Decl(unionsOfTupleTypes1.ts, 46, 7)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) +>0 : Symbol(0) + + let t41 = t4[1]; // number | undefined +>t41 : Symbol(t41, Decl(unionsOfTupleTypes1.ts, 47, 7)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) + + let t42 = t4[2]; // number | undefined +>t42 : Symbol(t42, Decl(unionsOfTupleTypes1.ts, 48, 7)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) + + let t4x = t4[x]; // string | number | boolean +>t4x : Symbol(t4x, Decl(unionsOfTupleTypes1.ts, 49, 7)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 25, 43)) + + t1[1] = 42; +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) +>1 : Symbol(1) + + t2[1] = 42; +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) +>1 : Symbol(1) + + t3[1] = 42; +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) + + t4[1] = 42; +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) +} + +// Repro from #27543 + +type Unioned = [string] | [string, number]; +>Unioned : Symbol(Unioned, Decl(unionsOfTupleTypes1.ts, 54, 1)) + +const ex: Unioned = ["hi"] as Unioned; +>ex : Symbol(ex, Decl(unionsOfTupleTypes1.ts, 59, 5)) +>Unioned : Symbol(Unioned, Decl(unionsOfTupleTypes1.ts, 54, 1)) +>Unioned : Symbol(Unioned, Decl(unionsOfTupleTypes1.ts, 54, 1)) + +const [x, y] = ex; +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 61, 7)) +>y : Symbol(y, Decl(unionsOfTupleTypes1.ts, 61, 9)) +>ex : Symbol(ex, Decl(unionsOfTupleTypes1.ts, 59, 5)) + diff --git a/tests/baselines/reference/unionsOfTupleTypes1.types b/tests/baselines/reference/unionsOfTupleTypes1.types new file mode 100644 index 00000000000..e44114f5a6a --- /dev/null +++ b/tests/baselines/reference/unionsOfTupleTypes1.types @@ -0,0 +1,266 @@ +=== tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts === +type T1 = [string, number]; +>T1 : [string, number] + +type T2 = [boolean] | [string, number]; +>T2 : T2 + +type T3 = [string, ...number[]]; +>T3 : [string, ...number[]] + +type T4 = [boolean] | [string, ...number[]]; +>T4 : T4 + +type T10 = T1[0]; // string +>T10 : string + +type T11 = T1[1]; // number +>T11 : number + +type T12 = T1[2]; // undefined +>T12 : undefined + +type T1N = T1[number]; // string | number +>T1N : string | number + +type T20 = T2[0]; // string | boolean +>T20 : string | boolean + +type T21 = T2[1]; // number | undefined +>T21 : number | undefined + +type T22 = T2[2]; // undefined +>T22 : undefined + +type T2N = T2[number]; // string | number | boolean +>T2N : string | number | boolean + +type T30 = T3[0]; // string +>T30 : string + +type T31 = T3[1]; // number +>T31 : number + +type T32 = T3[2]; // number +>T32 : number + +type T3N = T3[number]; // string | number +>T3N : string | number + +type T40 = T4[0]; // string | boolean +>T40 : string | boolean + +type T41 = T4[1]; // number | undefined +>T41 : number | undefined + +type T42 = T4[2]; // number | undefined +>T42 : number | undefined + +type T4N = T4[number]; // string | number | boolean +>T4N : string | number | boolean + +function f1(t1: T1, t2: T2, t3: T3, t4: T4, x: number) { +>f1 : (t1: [string, number], t2: T2, t3: [string, ...number[]], t4: T4, x: number) => void +>t1 : [string, number] +>t2 : T2 +>t3 : [string, ...number[]] +>t4 : T4 +>x : number + + let [d10, d11, d12] = t1; // string, number +>d10 : string +>d11 : number +>d12 : any +>t1 : [string, number] + + let [d20, d21, d22] = t2; // string | boolean, number | undefined +>d20 : string | boolean +>d21 : number | undefined +>d22 : any +>t2 : T2 + + let [d30, d31, d32] = t3; // string, number, number +>d30 : string +>d31 : number +>d32 : number +>t3 : [string, ...number[]] + + let [d40, d41, d42] = t4; // string | boolean, number | undefined, number | undefined +>d40 : string | boolean +>d41 : number | undefined +>d42 : number | undefined +>t4 : T4 + + [d10, d11, d12] = t1; +>[d10, d11, d12] = t1 : [string, number] +>[d10, d11, d12] : [string, number, any] +>d10 : string +>d11 : number +>d12 : any +>t1 : [string, number] + + [d20, d21, d22] = t2; +>[d20, d21, d22] = t2 : T2 +>[d20, d21, d22] : [string | boolean, number | undefined, any] +>d20 : string | boolean +>d21 : number | undefined +>d22 : any +>t2 : T2 + + [d30, d31, d32] = t3; +>[d30, d31, d32] = t3 : [string, ...number[]] +>[d30, d31, d32] : [string, number, number] +>d30 : string +>d31 : number +>d32 : number +>t3 : [string, ...number[]] + + [d40, d41, d42] = t4; +>[d40, d41, d42] = t4 : T4 +>[d40, d41, d42] : [string | boolean, number | undefined, number | undefined] +>d40 : string | boolean +>d41 : number | undefined +>d42 : number | undefined +>t4 : T4 + + let t10 = t1[0]; // string +>t10 : string +>t1[0] : string +>t1 : [string, number] +>0 : 0 + + let t11 = t1[1]; // number +>t11 : number +>t1[1] : number +>t1 : [string, number] +>1 : 1 + + let t12 = t1[2]; // undefined +>t12 : undefined +>t1[2] : undefined +>t1 : [string, number] +>2 : 2 + + let t1x = t1[x]; // string | number +>t1x : string | number +>t1[x] : string | number +>t1 : [string, number] +>x : number + + let t20 = t2[0]; // string | boolean +>t20 : string | boolean +>t2[0] : string | boolean +>t2 : T2 +>0 : 0 + + let t21 = t2[1]; // number | undefined +>t21 : number | undefined +>t2[1] : number | undefined +>t2 : T2 +>1 : 1 + + let t22 = t2[2]; // undefined +>t22 : undefined +>t2[2] : undefined +>t2 : T2 +>2 : 2 + + let t2x = t2[x]; // string | number | boolean +>t2x : string | number | boolean +>t2[x] : string | number | boolean +>t2 : T2 +>x : number + + let t30 = t3[0]; // string +>t30 : string +>t3[0] : string +>t3 : [string, ...number[]] +>0 : 0 + + let t31 = t3[1]; // number +>t31 : number +>t3[1] : number +>t3 : [string, ...number[]] +>1 : 1 + + let t32 = t3[2]; // number +>t32 : number +>t3[2] : number +>t3 : [string, ...number[]] +>2 : 2 + + let t3x = t3[x]; // string | number +>t3x : string | number +>t3[x] : string | number +>t3 : [string, ...number[]] +>x : number + + let t40 = t4[0]; // string | boolean +>t40 : string | boolean +>t4[0] : string | boolean +>t4 : T4 +>0 : 0 + + let t41 = t4[1]; // number | undefined +>t41 : number | undefined +>t4[1] : number | undefined +>t4 : T4 +>1 : 1 + + let t42 = t4[2]; // number | undefined +>t42 : number | undefined +>t4[2] : number | undefined +>t4 : T4 +>2 : 2 + + let t4x = t4[x]; // string | number | boolean +>t4x : string | number | boolean +>t4[x] : string | number | boolean +>t4 : T4 +>x : number + + t1[1] = 42; +>t1[1] = 42 : 42 +>t1[1] : number +>t1 : [string, number] +>1 : 1 +>42 : 42 + + t2[1] = 42; +>t2[1] = 42 : 42 +>t2[1] : number | undefined +>t2 : T2 +>1 : 1 +>42 : 42 + + t3[1] = 42; +>t3[1] = 42 : 42 +>t3[1] : number +>t3 : [string, ...number[]] +>1 : 1 +>42 : 42 + + t4[1] = 42; +>t4[1] = 42 : 42 +>t4[1] : number | undefined +>t4 : T4 +>1 : 1 +>42 : 42 +} + +// Repro from #27543 + +type Unioned = [string] | [string, number]; +>Unioned : Unioned + +const ex: Unioned = ["hi"] as Unioned; +>ex : Unioned +>["hi"] as Unioned : Unioned +>["hi"] : [string] +>"hi" : "hi" + +const [x, y] = ex; +>x : string +>y : number | undefined +>ex : Unioned + diff --git a/tests/baselines/reference/unknownSymbols1.js b/tests/baselines/reference/unknownSymbols1.js index 16879fefdc3..64057fe8c71 100644 --- a/tests/baselines/reference/unknownSymbols1.js +++ b/tests/baselines/reference/unknownSymbols1.js @@ -39,7 +39,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/unspecializedConstraints.js b/tests/baselines/reference/unspecializedConstraints.js index a1ef64044c7..4f1a9196156 100644 --- a/tests/baselines/reference/unspecializedConstraints.js +++ b/tests/baselines/reference/unspecializedConstraints.js @@ -160,7 +160,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.js b/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.js index 3bb62676288..d685742804f 100644 --- a/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.js +++ b/tests/baselines/reference/untypedFunctionCallsWithTypeParameters1.js @@ -50,7 +50,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/unusedClassesinNamespace4.js b/tests/baselines/reference/unusedClassesinNamespace4.js index df7d1f6b0e2..57517346ea3 100644 --- a/tests/baselines/reference/unusedClassesinNamespace4.js +++ b/tests/baselines/reference/unusedClassesinNamespace4.js @@ -20,7 +20,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/unusedIdentifiersConsolidated1.js b/tests/baselines/reference/unusedIdentifiersConsolidated1.js index b18ab04d08e..a26090bb617 100644 --- a/tests/baselines/reference/unusedIdentifiersConsolidated1.js +++ b/tests/baselines/reference/unusedIdentifiersConsolidated1.js @@ -108,7 +108,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/unusedInvalidTypeArguments.js b/tests/baselines/reference/unusedInvalidTypeArguments.js index 70840f0911a..1a424921c1f 100644 --- a/tests/baselines/reference/unusedInvalidTypeArguments.js +++ b/tests/baselines/reference/unusedInvalidTypeArguments.js @@ -59,7 +59,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -105,7 +105,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/useBeforeDeclaration_superClass.js b/tests/baselines/reference/useBeforeDeclaration_superClass.js index 637423f6d9f..01492e31d89 100644 --- a/tests/baselines/reference/useBeforeDeclaration_superClass.js +++ b/tests/baselines/reference/useBeforeDeclaration_superClass.js @@ -35,7 +35,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/user/acorn.log b/tests/baselines/reference/user/acorn.log index 7780ccb6e48..75c36a98697 100644 --- a/tests/baselines/reference/user/acorn.log +++ b/tests/baselines/reference/user/acorn.log @@ -15,43 +15,43 @@ node_modules/acorn/dist/acorn.es.js(545,15): error TS2339: Property 'parseTopLev node_modules/acorn/dist/acorn.es.js(558,14): error TS2531: Object is possibly 'null'. node_modules/acorn/dist/acorn.es.js(718,25): error TS2531: Object is possibly 'null'. node_modules/acorn/dist/acorn.es.js(738,25): error TS2531: Object is possibly 'null'. -node_modules/acorn/dist/acorn.es.js(2751,7): error TS2339: Property 'pos' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.es.js(2751,22): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.es.js(2751,37): error TS2339: Property 'raisedAt' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.es.js(2962,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2963,10): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2966,18): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2967,38): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2968,16): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2970,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2974,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2974,26): error TS2339: Property 'braceIsBlock' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2975,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2979,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2980,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2985,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2986,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2995,73): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2996,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2998,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2999,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3003,12): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3004,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3006,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3007,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3012,22): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3013,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2752,7): error TS2339: Property 'pos' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.es.js(2752,22): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.es.js(2752,37): error TS2339: Property 'raisedAt' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.es.js(2963,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2964,10): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2967,18): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2968,38): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2969,16): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2971,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2975,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2975,26): error TS2339: Property 'braceIsBlock' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2976,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2980,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2981,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2986,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2987,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2996,73): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2997,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2999,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3000,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3004,12): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3005,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3007,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3008,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3013,22): error TS2339: Property 'context' does not exist on type 'TokenType'. node_modules/acorn/dist/acorn.es.js(3014,14): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3016,14): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3018,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3023,12): error TS2339: Property 'options' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3024,14): error TS2339: Property 'value' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3024,38): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3015,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3017,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3019,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3024,12): error TS2339: Property 'options' does not exist on type 'TokenType'. node_modules/acorn/dist/acorn.es.js(3025,14): error TS2339: Property 'value' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3025,40): error TS2339: Property 'inGeneratorContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3028,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(5290,5): error TS2339: Property 'nextToken' does not exist on type 'Parser'. -node_modules/acorn/dist/acorn.es.js(5291,12): error TS2339: Property 'parseExpression' does not exist on type 'Parser'. +node_modules/acorn/dist/acorn.es.js(3025,38): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3026,14): error TS2339: Property 'value' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3026,40): error TS2339: Property 'inGeneratorContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3029,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(5291,5): error TS2339: Property 'nextToken' does not exist on type 'Parser'. +node_modules/acorn/dist/acorn.es.js(5292,12): error TS2339: Property 'parseExpression' does not exist on type 'Parser'. node_modules/acorn/dist/acorn.js(3,9): error TS2304: Cannot find name 'define'. node_modules/acorn/dist/acorn.js(3,34): error TS2304: Cannot find name 'define'. node_modules/acorn/dist/acorn.js(3,47): error TS2304: Cannot find name 'define'. @@ -64,43 +64,44 @@ node_modules/acorn/dist/acorn.js(551,15): error TS2339: Property 'parseTopLevel' node_modules/acorn/dist/acorn.js(564,14): error TS2531: Object is possibly 'null'. node_modules/acorn/dist/acorn.js(724,25): error TS2531: Object is possibly 'null'. node_modules/acorn/dist/acorn.js(744,25): error TS2531: Object is possibly 'null'. -node_modules/acorn/dist/acorn.js(2757,7): error TS2339: Property 'pos' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.js(2757,22): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.js(2757,37): error TS2339: Property 'raisedAt' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.js(2968,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2969,10): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2972,18): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2973,38): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2974,16): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2976,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2980,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2980,26): error TS2339: Property 'braceIsBlock' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2981,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2985,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2986,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2991,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2992,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3001,73): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3002,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3004,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3005,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3009,12): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3010,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3012,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3013,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3018,22): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3019,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2758,7): error TS2339: Property 'pos' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.js(2758,22): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.js(2758,37): error TS2339: Property 'raisedAt' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.js(2969,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2970,10): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2973,18): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2974,38): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2975,16): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2977,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2981,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2981,26): error TS2339: Property 'braceIsBlock' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2982,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2986,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2987,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2992,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2993,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3002,73): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3003,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3005,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3006,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3010,12): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3011,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3013,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3014,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3019,22): error TS2339: Property 'context' does not exist on type 'TokenType'. node_modules/acorn/dist/acorn.js(3020,14): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3022,14): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3024,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3029,12): error TS2339: Property 'options' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3030,14): error TS2339: Property 'value' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3030,38): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3021,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3023,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3025,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3030,12): error TS2339: Property 'options' does not exist on type 'TokenType'. node_modules/acorn/dist/acorn.js(3031,14): error TS2339: Property 'value' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3031,40): error TS2339: Property 'inGeneratorContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3034,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(5296,5): error TS2339: Property 'nextToken' does not exist on type 'Parser'. -node_modules/acorn/dist/acorn.js(5297,12): error TS2339: Property 'parseExpression' does not exist on type 'Parser'. +node_modules/acorn/dist/acorn.js(3031,38): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3032,14): error TS2339: Property 'value' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3032,40): error TS2339: Property 'inGeneratorContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3035,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(5297,5): error TS2339: Property 'nextToken' does not exist on type 'Parser'. +node_modules/acorn/dist/acorn.js(5298,12): error TS2339: Property 'parseExpression' does not exist on type 'Parser'. +node_modules/acorn/dist/acorn_loose.es.js(1,56): error TS2440: Import declaration conflicts with local declaration of 'defaultOptions'. node_modules/acorn/dist/acorn_loose.es.js(73,9): error TS2339: Property 'name' does not exist on type 'Node'. node_modules/acorn/dist/acorn_loose.es.js(79,9): error TS2339: Property 'value' does not exist on type 'Node'. node_modules/acorn/dist/acorn_loose.es.js(79,23): error TS2339: Property 'raw' does not exist on type 'Node'. diff --git a/tests/baselines/reference/user/adonis-framework.log b/tests/baselines/reference/user/adonis-framework.log index 6c7272790fe..a370c326c0a 100644 --- a/tests/baselines/reference/user/adonis-framework.log +++ b/tests/baselines/reference/user/adonis-framework.log @@ -35,14 +35,19 @@ node_modules/adonis-framework/src/Env/index.js(54,15): error TS2304: Cannot find node_modules/adonis-framework/src/Env/index.js(56,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Env/index.js(80,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Event/index.js(13,21): error TS2307: Cannot find module 'adonis-fold'. -node_modules/adonis-framework/src/Event/index.js(128,5): error TS2322: Type '() => {}[]' is not assignable to type 'any[]'. +node_modules/adonis-framework/src/Event/index.js(128,12): error TS2322: Type '() => {}[]' is not assignable to type 'any[]'. Property 'pop' is missing in type '() => {}[]'. node_modules/adonis-framework/src/Event/index.js(153,25): error TS2339: Property 'wildcard' does not exist on type 'EventEmitter2'. node_modules/adonis-framework/src/Event/index.js(188,17): error TS2304: Cannot find name 'Spread'. +node_modules/adonis-framework/src/Event/index.js(201,27): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. + Property 'pop' is missing in type 'IArguments'. node_modules/adonis-framework/src/Event/index.js(207,24): error TS2304: Cannot find name 'Sring'. node_modules/adonis-framework/src/Event/index.js(256,52): error TS2345: Argument of type 'Function' is not assignable to parameter of type 'Listener'. Type 'Function' provides no match for the signature '(...values: any[]): void'. node_modules/adonis-framework/src/Event/index.js(264,28): error TS2345: Argument of type 'Function' is not assignable to parameter of type 'Listener'. +node_modules/adonis-framework/src/Event/index.js(271,25): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[string, any, TimerHandler]'. + Property '0' is missing in type 'IArguments'. +node_modules/adonis-framework/src/Event/index.js(278,25): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[string, any, TimerHandler]'. node_modules/adonis-framework/src/Event/index.js(294,30): error TS2345: Argument of type 'Function' is not assignable to parameter of type 'Listener'. node_modules/adonis-framework/src/Exceptions/index.js(13,14): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. node_modules/adonis-framework/src/Exceptions/index.js(27,12): error TS2554: Expected 0 arguments, but got 3. @@ -107,6 +112,13 @@ node_modules/adonis-framework/src/Response/index.js(95,16): error TS2304: Cannot node_modules/adonis-framework/src/Response/index.js(172,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Response/index.js(299,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Response/index.js(323,15): error TS2304: Cannot find name 'Mixed'. +node_modules/adonis-framework/src/Route/ResourceCollection.js(43,40): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. + Property 'pop' is missing in type 'IArguments'. +node_modules/adonis-framework/src/Route/ResourceCollection.js(56,31): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. +node_modules/adonis-framework/src/Route/ResourceMember.js(43,40): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. +node_modules/adonis-framework/src/Route/ResourceMember.js(56,31): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. +node_modules/adonis-framework/src/Route/group.js(34,31): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. +node_modules/adonis-framework/src/Route/group.js(43,41): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. node_modules/adonis-framework/src/Route/helpers.js(22,13): error TS2304: Cannot find name 'Any'. node_modules/adonis-framework/src/Route/helpers.js(34,3): error TS2322: Type 'string | string[]' is not assignable to type 'string'. Type 'string[]' is not assignable to type 'string'. @@ -120,6 +132,8 @@ node_modules/adonis-framework/src/Route/index.js(259,21): error TS2345: Argument node_modules/adonis-framework/src/Route/index.js(280,21): error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'string'. node_modules/adonis-framework/src/Route/index.js(321,13): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Route/index.js(321,20): error TS8029: JSDoc '@param' tag has name 'keys', but there is no parameter with that name. It would match 'arguments' if it had an array type. +node_modules/adonis-framework/src/Route/index.js(333,29): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. +node_modules/adonis-framework/src/Route/index.js(343,33): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. node_modules/adonis-framework/src/Route/index.js(354,20): error TS2694: Namespace 'Route' has no exported member 'Group'. node_modules/adonis-framework/src/Route/index.js(368,3): error TS2322: Type 'null' is not assignable to type 'string'. node_modules/adonis-framework/src/Route/index.js(396,10): error TS2554: Expected 2 arguments, but got 3. @@ -133,11 +147,16 @@ node_modules/adonis-framework/src/Route/resource.js(96,25): error TS2345: Argume node_modules/adonis-framework/src/Route/resource.js(97,25): error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'string'. node_modules/adonis-framework/src/Route/resource.js(172,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Route/resource.js(172,22): error TS8029: JSDoc '@param' tag has name 'methods', but there is no parameter with that name. It would match 'arguments' if it had an array type. +node_modules/adonis-framework/src/Route/resource.js(183,45): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. node_modules/adonis-framework/src/Route/resource.js(198,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Route/resource.js(198,22): error TS8029: JSDoc '@param' tag has name 'methods', but there is no parameter with that name. It would match 'arguments' if it had an array type. +node_modules/adonis-framework/src/Route/resource.js(209,45): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. node_modules/adonis-framework/src/Route/resource.js(233,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Route/resource.js(261,15): error TS2304: Cannot find name 'Mixed'. +node_modules/adonis-framework/src/Route/resource.js(290,40): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any, ...any[]]'. + Property '0' is missing in type 'IArguments'. node_modules/adonis-framework/src/Route/resource.js(296,15): error TS2304: Cannot find name 'Mixed'. +node_modules/adonis-framework/src/Route/resource.js(314,62): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. node_modules/adonis-framework/src/Server/helpers.js(17,29): error TS8024: JSDoc '@param' tag has name 'appNamespace', but there is no parameter with that name. node_modules/adonis-framework/src/Server/index.js(17,21): error TS2307: Cannot find module 'adonis-fold'. node_modules/adonis-framework/src/Server/index.js(54,21): error TS2554: Expected 4 arguments, but got 3. diff --git a/tests/baselines/reference/user/assert.log b/tests/baselines/reference/user/assert.log index 37a2c42e4d6..ab73398f14c 100644 --- a/tests/baselines/reference/user/assert.log +++ b/tests/baselines/reference/user/assert.log @@ -25,17 +25,17 @@ node_modules/assert/test.js(143,10): error TS2339: Property 'a' does not exist o node_modules/assert/test.js(149,5): error TS2552: Cannot find name 'test'. Did you mean 'tests'? node_modules/assert/test.js(157,51): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'never' has no compatible call signatures. node_modules/assert/test.js(161,5): error TS2552: Cannot find name 'test'. Did you mean 'tests'? -node_modules/assert/test.js(168,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(182,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(229,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(235,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(250,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(254,5): error TS2304: Cannot find name 'test'. +node_modules/assert/test.js(168,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(182,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(229,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(235,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(250,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(254,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. node_modules/assert/test.js(256,55): error TS2345: Argument of type 'TypeError' is not assignable to parameter of type 'string'. -node_modules/assert/test.js(262,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(279,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(285,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(320,5): error TS2304: Cannot find name 'test'. +node_modules/assert/test.js(262,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(279,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(285,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(320,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. diff --git a/tests/baselines/reference/user/async.log b/tests/baselines/reference/user/async.log index 3e7e3ab4c4b..32b54ba4a0e 100644 --- a/tests/baselines/reference/user/async.log +++ b/tests/baselines/reference/user/async.log @@ -51,7 +51,7 @@ node_modules/async/autoInject.js(160,28): error TS2695: Left side of comma opera node_modules/async/autoInject.js(164,14): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/autoInject.js(168,6): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/cargo.js(62,12): error TS2304: Cannot find name 'AsyncFunction'. -node_modules/async/cargo.js(67,14): error TS2304: Cannot find name 'module'. +node_modules/async/cargo.js(67,14): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. node_modules/async/cargo.js(67,20): error TS1005: '}' expected. node_modules/async/cargo.js(92,11): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/compose.js(8,37): error TS2695: Left side of comma operator is unused and has no side effects. @@ -92,8 +92,6 @@ node_modules/async/dist/async.js(31,29): error TS1003: Identifier expected. node_modules/async/dist/async.js(31,30): error TS1003: Identifier expected. node_modules/async/dist/async.js(257,56): error TS2339: Property 'Object' does not exist on type 'Window'. node_modules/async/dist/async.js(298,7): error TS2454: Variable 'unmasked' is used before being assigned. -node_modules/async/dist/async.js(480,35): error TS2538: Type 'true' cannot be used as an index type. -node_modules/async/dist/async.js(480,59): error TS2538: Type 'true' cannot be used as an index type. node_modules/async/dist/async.js(622,80): error TS2339: Property 'nodeType' does not exist on type 'NodeModule'. node_modules/async/dist/async.js(748,84): error TS2339: Property 'nodeType' does not exist on type 'NodeModule'. node_modules/async/dist/async.js(754,49): error TS2339: Property 'process' does not exist on type 'false | Global'. @@ -523,8 +521,6 @@ node_modules/async/internal/filter.js(64,29): error TS2695: Left side of comma o node_modules/async/internal/filter.js(66,18): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/internal/filter.js(72,19): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/internal/filter.js(73,27): error TS2695: Left side of comma operator is unused and has no side effects. -node_modules/async/internal/getIterator.js(8,35): error TS2538: Type 'true' cannot be used as an index type. -node_modules/async/internal/getIterator.js(8,59): error TS2538: Type 'true' cannot be used as an index type. node_modules/async/internal/initialParams.js(9,21): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/internal/iterator.js(41,18): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/internal/iterator.js(51,10): error TS2695: Left side of comma operator is unused and has no side effects. diff --git a/tests/baselines/reference/user/bluebird.log b/tests/baselines/reference/user/bluebird.log index 35d6d9ca05b..4d7acc487ae 100644 --- a/tests/baselines/reference/user/bluebird.log +++ b/tests/baselines/reference/user/bluebird.log @@ -20,6 +20,10 @@ node_modules/bluebird/js/release/debuggability.js(168,17): error TS2403: Subsequ node_modules/bluebird/js/release/debuggability.js(174,26): error TS2339: Property 'detail' does not exist on type 'Event'. node_modules/bluebird/js/release/debuggability.js(175,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. node_modules/bluebird/js/release/debuggability.js(176,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. +node_modules/bluebird/js/release/debuggability.js(199,48): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '["multipleResolves", MultipleResolveListener]'. + Property '0' is missing in type 'IArguments'. +node_modules/bluebird/js/release/debuggability.js(242,56): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. + Property 'pop' is missing in type 'IArguments'. node_modules/bluebird/js/release/debuggability.js(491,19): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/debuggability.js(562,46): error TS2554: Expected 0 arguments, but got 1. node_modules/bluebird/js/release/debuggability.js(736,5): error TS2721: Cannot invoke an object which is possibly 'null'. @@ -50,6 +54,7 @@ node_modules/bluebird/js/release/map.js(111,23): error TS2339: Property '_values node_modules/bluebird/js/release/map.js(113,18): error TS2339: Property '_isResolved' does not exist on type 'MappingPromiseArray'. node_modules/bluebird/js/release/map.js(127,10): error TS2339: Property '_resolve' does not exist on type 'MappingPromiseArray'. node_modules/bluebird/js/release/map.js(156,66): error TS2339: Property 'promise' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/method.js(15,46): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. node_modules/bluebird/js/release/nodeback.js(21,20): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: {}) => string[]) | ((o: any) => string[])' has no compatible call signatures. node_modules/bluebird/js/release/nodeify.js(32,19): error TS2339: Property 'cause' does not exist on type 'Error'. node_modules/bluebird/js/release/promise.js(4,12): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. @@ -78,6 +83,9 @@ node_modules/bluebird/js/release/promise.js(305,10): error TS2339: Property '_fi node_modules/bluebird/js/release/promise.js(322,10): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(339,42): error TS2339: Property '_isBound' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(434,26): error TS2339: Property '_propagateFrom' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(454,31): error TS2339: Property '_value' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(456,30): error TS2339: Property '_reason' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(459,17): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(471,14): error TS2339: Property '_warn' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(473,10): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(480,10): error TS2339: Property '_captureStackTrace' does not exist on type 'Promise'. @@ -85,6 +93,10 @@ node_modules/bluebird/js/release/promise.js(481,10): error TS2339: Property '_pu node_modules/bluebird/js/release/promise.js(483,18): error TS2339: Property '_execute' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(489,10): error TS2339: Property '_popContext' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(506,19): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. +node_modules/bluebird/js/release/promise.js(558,22): error TS2339: Property '_promiseCancelled' does not exist on type '{}'. +node_modules/bluebird/js/release/promise.js(572,23): error TS2339: Property '_isResolved' does not exist on type '{}'. +node_modules/bluebird/js/release/promise.js(574,26): error TS2339: Property '_promiseFulfilled' does not exist on type '{}'. +node_modules/bluebird/js/release/promise.js(576,26): error TS2339: Property '_promiseRejected' does not exist on type '{}'. node_modules/bluebird/js/release/promise.js(630,14): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(642,14): error TS2339: Property '_dereferenceTrace' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(659,14): error TS2339: Property '_ensurePossibleRejectionHandled' does not exist on type 'Promise'. diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 6085bb91b9e..77638fea091 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -11,8 +11,8 @@ Standard output: ../../../../built/local/lib.dom.d.ts(11899,13): error TS2300: Duplicate identifier 'Request'. ../../../../built/local/lib.dom.d.ts(16316,11): error TS2300: Duplicate identifier 'Window'. ../../../../built/local/lib.dom.d.ts(16447,13): error TS2300: Duplicate identifier 'Window'. -../../../../built/local/lib.es5.d.ts(1346,11): error TS2300: Duplicate identifier 'ArrayLike'. -../../../../built/local/lib.es5.d.ts(1382,6): error TS2300: Duplicate identifier 'Record'. +../../../../built/local/lib.es5.d.ts(1406,11): error TS2300: Duplicate identifier 'ArrayLike'. +../../../../built/local/lib.es5.d.ts(1442,6): error TS2300: Duplicate identifier 'Record'. ../../../../node_modules/@types/node/index.d.ts(150,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'module' must be of type '{}', but here has type 'NodeModule'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(43,8): error TS2339: Property '_importScriptPathPrefix' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(95,28): error TS2339: Property 'response' does not exist on type 'EventTarget'. @@ -29,10 +29,8 @@ node_modules/chrome-devtools-frontend/front_end/Runtime.js(270,9): error TS2322: Type 'void' is not assignable to type 'undefined'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(280,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(283,7): error TS2554: Expected 2-3 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/Runtime.js(527,9): error TS2322: Type 'Function' is not assignable to type 'new () => any'. - Type 'Function' provides no match for the signature 'new (): any'. -node_modules/chrome-devtools-frontend/front_end/Runtime.js(527,49): error TS2352: Conversion of type 'Window' to type 'Function' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Property 'apply' is missing in type 'Window'. +node_modules/chrome-devtools-frontend/front_end/Runtime.js(527,49): error TS2352: Conversion of type 'Window' to type 'new () => any' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. + Type 'Window' provides no match for the signature 'new (): any'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(539,20): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. node_modules/chrome-devtools-frontend/front_end/Runtime.js(693,7): error TS2322: Type 'Promise' is not assignable to type 'Promise'. Type 'boolean' is not assignable to type 'undefined'. @@ -46,15 +44,26 @@ node_modules/chrome-devtools-frontend/front_end/Runtime.js(1088,15): error TS235 node_modules/chrome-devtools-frontend/front_end/Tests.js(107,5): error TS2322: Type 'Timer' is not assignable to type 'number'. node_modules/chrome-devtools-frontend/front_end/Tests.js(208,5): error TS2554: Expected 4 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/Tests.js(221,7): error TS2554: Expected 4 arguments, but got 3. +node_modules/chrome-devtools-frontend/front_end/Tests.js(378,17): error TS2339: Property 'sources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/Tests.js(397,5): error TS2554: Expected 4 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/Tests.js(416,5): error TS2554: Expected 4 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/Tests.js(440,5): error TS2554: Expected 4 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/Tests.js(475,5): error TS2554: Expected 4 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/Tests.js(571,33): error TS2339: Property 'deprecatedRunAfterPendingDispatches' does not exist on type 'typeof InspectorBackend'. node_modules/chrome-devtools-frontend/front_end/Tests.js(590,27): error TS2554: Expected 0 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/Tests.js(619,44): error TS2339: Property 'emulationAgent' does not exist on type 'Target'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(666,38): error TS2339: Property 'inputAgent' does not exist on type 'Target'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(668,38): error TS2339: Property 'inputAgent' does not exist on type 'Target'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(673,38): error TS2339: Property 'inputAgent' does not exist on type 'Target'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(675,38): error TS2339: Property 'inputAgent' does not exist on type 'Target'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(677,38): error TS2339: Property 'inputAgent' does not exist on type 'Target'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(679,38): error TS2339: Property 'inputAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/Tests.js(687,7): error TS2554: Expected 3 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/Tests.js(711,7): error TS2554: Expected 3 arguments, but got 2. +node_modules/chrome-devtools-frontend/front_end/Tests.js(717,36): error TS2339: Property 'inputAgent' does not exist on type 'Target'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(719,36): error TS2339: Property 'inputAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/Tests.js(735,5): error TS2554: Expected 4 arguments, but got 3. +node_modules/chrome-devtools-frontend/front_end/Tests.js(814,38): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/Tests.js(816,7): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/Tests.js(847,9): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/Tests.js(848,9): error TS2554: Expected 2 arguments, but got 1. @@ -86,10 +95,14 @@ node_modules/chrome-devtools-frontend/front_end/Tests.js(977,11): error TS2554: node_modules/chrome-devtools-frontend/front_end/Tests.js(978,11): error TS2554: Expected 3 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/Tests.js(986,5): error TS2554: Expected 3 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/Tests.js(988,5): error TS2554: Expected 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/Tests.js(1033,32): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(1040,30): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(1084,27): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/Tests.js(1139,33): error TS2339: Property 'ConsoleView' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/Tests.js(1142,31): error TS2339: Property 'ConsoleView' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/Tests.js(1186,5): error TS2554: Expected 4 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/Tests.js(1199,9): error TS2554: Expected 4 arguments, but got 3. +node_modules/chrome-devtools-frontend/front_end/Tests.js(1199,35): error TS2339: Property 'sources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/Tests.js(1229,10): error TS2339: Property 'uiTests' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/Tests.js(1229,41): error TS2339: Property 'domAutomationController' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAAttributesView.js(9,11): error TS2554: Expected 2 arguments, but got 1. @@ -109,10 +122,8 @@ node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAAttributesView node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAAttributesView.js(182,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAAttributesView.js(209,39): error TS2694: Namespace 'UI.SuggestBox' has no exported member 'Suggestions'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAAttributesView.js(213,36): error TS2339: Property '_isEditingName' does not exist on type 'ARIAAttributePrompt'. -node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAConfig.js(5,28): error TS2339: Property '_config' does not exist on type 'typeof ARIAMetadata'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAMetadata.js(56,35): error TS2339: Property '_instance' does not exist on type 'typeof ARIAMetadata'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAMetadata.js(57,32): error TS2339: Property '_instance' does not exist on type 'typeof ARIAMetadata'. -node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAMetadata.js(57,102): error TS2339: Property '_config' does not exist on type 'typeof ARIAMetadata'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAMetadata.js(58,37): error TS2339: Property '_instance' does not exist on type 'typeof ARIAMetadata'. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(10,11): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(14,18): error TS2339: Property 'tabIndex' does not exist on type 'Element'. @@ -297,6 +308,12 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(2 node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(21,32): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(26,32): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(36,47): error TS2339: Property 'AnimationModel' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. +node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(36,63): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'AnimationTimeline' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(animationModel: AnimationModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'animationModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'AnimationModel'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(44,67): error TS2339: Property 'AnimationModel' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(52,67): error TS2339: Property 'AnimationModel' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(80,19): error TS2339: Property 'AnimationModel' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. @@ -307,14 +324,11 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(1 node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(105,28): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(110,48): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(112,44): error TS2554: Expected 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(114,34): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(117,46): error TS2554: Expected 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(119,34): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(123,40): error TS2339: Property 'AnimationTimeline' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(125,45): error TS2345: Argument of type 'TemplateStringsArray' is not assignable to parameter of type 'string | string[]'. Type 'TemplateStringsArray' is not assignable to type 'string[]'. + Property 'pop' is missing in type 'TemplateStringsArray'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(125,72): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(128,24): error TS2345: Argument of type 'TemplateStringsArray' is not assignable to parameter of type 'string | string[]'. Type 'TemplateStringsArray' is not assignable to type 'string[]'. @@ -324,8 +338,6 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(1 node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(139,41): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(144,48): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(145,36): error TS2339: Property 'AnimationTimeline' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. -node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(148,31): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(165,19): error TS2694: Namespace 'UI' has no exported member 'PopoverRequest'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(169,18): error TS2339: Property 'isDescendant' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(173,25): error TS2339: Property 'boxInWindow' does not exist on type 'EventTarget'. @@ -354,10 +366,10 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(4 node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(450,37): error TS2339: Property 'AnimationUI' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(457,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(484,36): error TS2339: Property 'millisToString' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(566,9): error TS2345: Argument of type '{ transform: string; }[]' is not assignable to parameter of type 'PropertyIndexedKeyframes | Keyframe[]'. - Type '{ transform: string; }[]' is not assignable to type 'Keyframe[]'. - Type '{ transform: string; }' is not assignable to type 'Keyframe'. - Property 'alignContent' is missing in type '{ transform: string; }'. +node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(566,10): error TS2322: Type '{ transform: string; }' is not assignable to type 'string | string[] | Keyframe'. + Type '{ transform: string; }' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(566,42): error TS2322: Type '{ transform: string; }' is not assignable to type 'string | string[] | Keyframe'. + Type '{ transform: string; }' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(571,18): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(587,44): error TS2339: Property 'millisToString' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(589,20): error TS2339: Property 'window' does not exist on type 'Element'. @@ -431,27 +443,41 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationUI.js(380,11) node_modules/chrome-devtools-frontend/front_end/animation/AnimationUI.js(387,11): error TS2339: Property 'AnimationUI' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationUI.js(394,11): error TS2339: Property 'AnimationUI' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationUI.js(402,11): error TS2339: Property 'AnimationUI' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. -node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(32,5): error TS2304: Cannot find name 'promise'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/AppcacheTestRunner.js(53,47): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/AppcacheTestRunner.js(102,25): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/AppcacheTestRunner.js(130,39): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/AppcacheTestRunner.js(131,36): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(11,13): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(13,13): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(19,13): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(21,37): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(32,5): error TS2552: Cannot find name 'promise'. Did you mean 'Promise'? node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(40,11): error TS2304: Cannot find name 'promise'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(61,13): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(68,37): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(70,13): error TS2339: Property 'resources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(135,10): error TS2554: Expected 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/IndexedDBTestRunner.js(12,40): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/IndexedDBTestRunner.js(47,42): error TS2339: Property 'resources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/application_test_runner/IndexedDBTestRunner.js(140,24): error TS2554: Expected 1 arguments, but got 2. -node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(16,50): error TS2345: Argument of type '(msg: string) => void' is not assignable to parameter of type '(arg0: string) => undefined'. - Type 'void' is not assignable to type 'undefined'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/ResourceTreeTestRunner.js(69,18): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/ResourcesTestRunner.js(76,15): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/ResourcesTestRunner.js(77,33): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/ServiceWorkersTestRunner.js(44,26): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(16,57): error TS2322: Type 'void' is not assignable to type 'undefined'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(16,76): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(20,42): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(21,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(24,47): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(25,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(31,31): error TS2345: Argument of type 'ToolbarComboBox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarComboBox' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarComboBox'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(33,44): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(34,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(37,53): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(39,57): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(45,63): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'Audits2Panel' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(serviceWorkerManager: ServiceWorkerManager) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'serviceWorkerManager' and 'model' are incompatible. + Type 'T' is not assignable to type 'ServiceWorkerManager'. +node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(94,50): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(126,14): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(135,14): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(147,42): error TS2555: Expected at least 2 arguments, but got 1. @@ -468,6 +494,7 @@ node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(229,29): node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(230,23): error TS2339: Property 'autofocus' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(233,46): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(252,7): error TS2322: Type 'Promise' is not assignable to type 'Promise'. +node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(256,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(276,31): error TS2339: Property 'singleton' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(302,30): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(342,26): error TS2555: Expected at least 2 arguments, but got 1. @@ -502,6 +529,7 @@ node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(690,15): node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(701,15): error TS2503: Cannot find namespace 'ReportRenderer'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(718,22): error TS2551: Property 'Preset' does not exist on type 'typeof Audits2Panel'. Did you mean 'Presets'? node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(720,42): error TS2694: Namespace 'Audits2.Audits2Panel' has no exported member 'Preset'. +node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(772,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(780,25): error TS2503: Cannot find namespace 'ReportRenderer'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(832,25): error TS2503: Cannot find namespace 'ReportRenderer'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(901,15): error TS2503: Cannot find namespace 'ReportRenderer'. @@ -669,6 +697,8 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9117,1): error TS2554: Expected 0-2 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9467,15): error TS2339: Property 'axe' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9708,34): error TS2345: Argument of type 'any[][]' is not assignable to parameter of type 'ReadonlyArray<[any, any]>'. + Type 'any[]' is not assignable to type '[any, any]'. + Property '0' is missing in type 'any[]'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9948,10): error TS2693: 'ShadowRoot' only refers to a type, but is being used as a value here. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9969,4): error TS2693: 'ShadowRoot' only refers to a type, but is being used as a value here. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(10092,16): error TS2304: Cannot find name 'd41d8cd98f00b204e9800998ecf8427e_LibraryDetectorTests'. @@ -843,6 +873,16 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24079,1): error TS2323: Cannot redeclare exported variable 'Buf16'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24080,1): error TS2323: Cannot redeclare exported variable 'Buf32'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(26059,1): error TS2323: Cannot redeclare exported variable 'deflate'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27915,27): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27918,30): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27921,30): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27928,27): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27929,20): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27956,16): error TS2323: Cannot redeclare exported variable 'parse'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(28222,51): error TS2300: Duplicate identifier '_read'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(28457,20): error TS2339: Property 'emit' does not exist on type 'Readable'. @@ -1257,7 +1297,7 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(44340,15): error TS2339: Property 'valuesArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(44348,15): error TS2339: Property 'keysArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(44356,15): error TS2339: Property 'inverse' does not exist on type 'Map'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(44361,8): error TS2339: Property 'set' does not exist on type 'Multimap'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(44458,18): error TS2339: Property 'keysArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(44469,8): error TS2339: Property 'pushAll' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(44495,27): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(44584,6): error TS2339: Property 'setImmediate' does not exist on type 'Window'. @@ -2978,7 +3018,6 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65576,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'comment' must be of type '{ multiLine: boolean; slice: any[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]', but here has type '{ multiLine: boolean; slice: number[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67117,1): error TS2322: Type 'string[]' is not assignable to type 'RegExpExecArray'. Property 'index' is missing in type 'string[]'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67167,19): error TS2339: Property 'parse' does not exist on type 'Link'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67300,14): error TS2339: Property 'Channels' does not exist on type '{}'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67300,35): error TS2339: Property 'Channels' does not exist on type '{}'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67301,24): error TS2339: Property 'Channels' does not exist on type '{}'. @@ -3018,6 +3057,12 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker.js(5,11): error TS2339: Property 'Runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/audits2_worker.js(6,8): error TS2339: Property 'importScripts' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(25,71): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. +node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(30,56): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'BlackboxManager' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(debuggerModel: DebuggerModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'debuggerModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'DebuggerModel'. node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(69,72): error TS2339: Property 'getAsArray' does not exist on type 'Setting'. node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(89,27): error TS2339: Property 'lowerBound' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(94,26): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. @@ -3038,6 +3083,12 @@ node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(362, node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(375,9): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(378,9): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(381,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. +node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(60,52): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'BreakpointManager' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(debuggerModel: DebuggerModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'debuggerModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'DebuggerModel'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(97,52): error TS2339: Property 'get' does not exist on type 'Multimap'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(120,52): error TS2339: Property 'valuesArray' does not exist on type 'Multimap'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(123,34): error TS2339: Property 'clear' does not exist on type 'Multimap'. @@ -3058,12 +3109,28 @@ node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(44 node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(444,23): error TS2339: Property 'remove' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(446,19): error TS2339: Property 'remove' does not exist on type 'Map>'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(448,40): error TS2339: Property 'remove' does not exist on type 'Map>>'. +node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(518,77): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'Breakpoint' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(debuggerModel: DebuggerModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'debuggerModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'DebuggerModel'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(536,50): error TS2339: Property 'remove' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(655,51): error TS2339: Property 'valuesArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(667,51): error TS2339: Property 'valuesArray' does not exist on type 'Map'. +node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(674,79): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'Breakpoint' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(debuggerModel: DebuggerModel) => void' is not assignable to type '(model: T) => void'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(713,51): error TS2339: Property 'valuesArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(863,24): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(905,22): error TS2694: Namespace 'Common' has no exported member 'Event'. +node_modules/chrome-devtools-frontend/front_end/bindings/CSSWorkspaceBinding.js(20,47): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'CSSWorkspaceBinding' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(cssModel: CSSModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'cssModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'CSSModel'. node_modules/chrome-devtools-frontend/front_end/bindings/CSSWorkspaceBinding.js(104,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'rawLocations' must be of type 'CSSLocation[]', but here has type 'any[]'. node_modules/chrome-devtools-frontend/front_end/bindings/CSSWorkspaceBinding.js(106,20): error TS2339: Property 'pushAll' does not exist on type 'CSSLocation[]'. node_modules/chrome-devtools-frontend/front_end/bindings/CSSWorkspaceBinding.js(126,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -3086,8 +3153,13 @@ node_modules/chrome-devtools-frontend/front_end/bindings/CompilerScriptMapping.j node_modules/chrome-devtools-frontend/front_end/bindings/CompilerScriptMapping.js(202,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/bindings/CompilerScriptMapping.js(218,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/bindings/ContentProviderBasedProject.js(180,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. +node_modules/chrome-devtools-frontend/front_end/bindings/DebuggerWorkspaceBinding.js(26,52): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'DebuggerWorkspaceBinding' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(debuggerModel: DebuggerModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'debuggerModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'DebuggerModel'. node_modules/chrome-devtools-frontend/front_end/bindings/DebuggerWorkspaceBinding.js(51,31): error TS2339: Property 'remove' does not exist on type 'Map'. -node_modules/chrome-devtools-frontend/front_end/bindings/DebuggerWorkspaceBinding.js(85,5): error TS2322: Type 'StackTraceTopFrameLocation' is not assignable to type '{ update(): void; uiLocation(): UILocation; dispose(): void; isBlackboxed(): boolean; }'. node_modules/chrome-devtools-frontend/front_end/bindings/DebuggerWorkspaceBinding.js(85,5): error TS2322: Type 'StackTraceTopFrameLocation' is not assignable to type '{ update(): void; uiLocation(): UILocation; dispose(): void; isBlackboxed(): boolean; }'. Property '_updateScheduled' does not exist on type '{ update(): void; uiLocation(): UILocation; dispose(): void; isBlackboxed(): boolean; }'. node_modules/chrome-devtools-frontend/front_end/bindings/DebuggerWorkspaceBinding.js(195,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -3118,6 +3190,12 @@ node_modules/chrome-devtools-frontend/front_end/bindings/NetworkProject.js(286,2 node_modules/chrome-devtools-frontend/front_end/bindings/NetworkProject.js(308,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/bindings/PresentationConsoleMessageHelper.js(66,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/bindings/PresentationConsoleMessageHelper.js(130,22): error TS2694: Namespace 'Common' has no exported member 'Event'. +node_modules/chrome-devtools-frontend/front_end/bindings/ResourceMapping.js(17,56): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'ResourceMapping' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(resourceTreeModel: ResourceTreeModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'resourceTreeModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'ResourceTreeModel'. node_modules/chrome-devtools-frontend/front_end/bindings/ResourceMapping.js(147,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/bindings/ResourceMapping.js(181,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/bindings/ResourceMapping.js(189,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -3142,6 +3220,7 @@ node_modules/chrome-devtools-frontend/front_end/bindings/ResourceScriptMapping.j node_modules/chrome-devtools-frontend/front_end/bindings/ResourceScriptMapping.js(323,14): error TS2339: Property '_scriptSource' does not exist on type 'ResourceScriptFile'. node_modules/chrome-devtools-frontend/front_end/bindings/ResourceScriptMapping.js(384,38): error TS2339: Property '_scriptSource' does not exist on type 'ResourceScriptFile'. node_modules/chrome-devtools-frontend/front_end/bindings/ResourceScriptMapping.js(395,12): error TS2339: Property '_scriptSource' does not exist on type 'ResourceScriptFile'. +node_modules/chrome-devtools-frontend/front_end/bindings/ResourceUtils.js(72,32): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/bindings/SASSSourceMapping.js(63,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/bindings/SASSSourceMapping.js(90,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/bindings/SASSSourceMapping.js(108,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -3216,14 +3295,10 @@ node_modules/chrome-devtools-frontend/front_end/changes/ChangesSidebar.js(38,22) node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(26,44): error TS2694: Namespace 'Changes.ChangesView' has no exported member 'Row'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(37,42): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(43,45): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(45,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(47,37): error TS2345: Argument of type 'ToolbarText' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarText' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(50,20): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(75,11): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(111,22): error TS2554: Expected 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(133,20): error TS2694: Namespace 'Diff' has no exported member 'Diff'. +node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(133,25): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(139,22): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(155,26): error TS2339: Property 'pushAll' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(156,25): error TS2339: Property 'pushAll' does not exist on type 'any[]'. @@ -3389,9 +3464,9 @@ node_modules/chrome-devtools-frontend/front_end/cm/overlay.js(16,43): error TS23 node_modules/chrome-devtools-frontend/front_end/cm/overlay.js(17,5): error TS2304: Cannot find name 'define'. node_modules/chrome-devtools-frontend/front_end/cm_headless/headlesscodemirror.js(30,14): error TS2403: Subsequent variable declarations must have the same type. Variable 'ok' must be of type 'boolean', but here has type 'any'. node_modules/chrome-devtools-frontend/front_end/cm_headless/headlesscodemirror.js(74,1): error TS2719: Type 'typeof StringStream' is not assignable to type 'typeof StringStream'. Two different types with this name exist, but they are unrelated. - Type 'StringStream' is not assignable to type 'StringStream & { backUp: (n: any) => void; column: () => void; current: () => void; eat: (match: any) => void; eatSpace: () => void; eatWhile: (match: any) => void; eol: () => void; indentation: () => void; ... 5 more ...; sol: () => void; }'. - Type 'StringStream' is not assignable to type '{ backUp: (n: any) => void; column: () => void; current: () => void; eat: (match: any) => void; eatSpace: () => void; eatWhile: (match: any) => void; eol: () => void; indentation: () => void; match: (pattern: string | RegExp, consume?: boolean, caseInsensitive?: boolean) => void; ... 4 more ...; sol: () => void; }'. - Property 'backUp' is missing in type 'StringStream'. + Types of property 'prototype' are incompatible. + Type '{ eol: () => boolean; sol: () => boolean; peek: () => any; next: () => any; eat: (match: any) => any; eatWhile: (match: any) => boolean; eatSpace: () => boolean; skipToEnd: typeof skipToEnd; skipTo: typeof skipTo; backUp: (n: any) => void; ... 5 more ...; lookAhead: () => any; }' is not assignable to type '{ backUp: (n: any) => void; column: () => void; current: () => void; eat: (match: any) => void; eatSpace: () => void; eatWhile: (match: any) => void; eol: () => void; indentation: () => void; match: (pattern: string | RegExp, consume?: boolean, caseInsensitive?: boolean) => void; ... 4 more ...; sol: () => void; }'. + Property 'hideFirstChars' does not exist on type '{ backUp: (n: any) => void; column: () => void; current: () => void; eat: (match: any) => void; eatSpace: () => void; eatWhile: (match: any) => void; eol: () => void; indentation: () => void; match: (pattern: string | RegExp, consume?: boolean, caseInsensitive?: boolean) => void; ... 4 more ...; sol: () => void; }'. node_modules/chrome-devtools-frontend/front_end/cm_headless/headlesscodemirror.js(87,12): error TS2339: Property 'resolveMode' does not exist on type 'typeof CodeMirror'. node_modules/chrome-devtools-frontend/front_end/cm_headless/headlesscodemirror.js(97,21): error TS2339: Property 'resolveMode' does not exist on type 'typeof CodeMirror'. node_modules/chrome-devtools-frontend/front_end/cm_headless/headlesscodemirror.js(102,12): error TS2339: Property 'registerHelper' does not exist on type 'typeof CodeMirror'. @@ -3482,13 +3557,9 @@ node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js( node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(39,42): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(42,46): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(58,47): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(61,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(63,43): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(76,39): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(82,30): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(85,37): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(125,27): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(136,28): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/color_picker/ContrastDetails.js(178,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -3504,20 +3575,14 @@ node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(48,25): node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(51,46): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(58,46): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(60,52): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(64,31): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(84,18): error TS2339: Property 'maxLength' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(97,20): error TS2339: Property 'maxLength' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(126,52): error TS2694: Namespace 'ColorPicker.Spectrum' has no exported member 'Palette'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(128,46): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(130,57): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(133,49): error TS2339: Property 'createChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(144,47): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(146,39): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(150,47): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(152,45): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(166,12): error TS2339: Property '_hueAlphaLeft' does not exist on type 'Spectrum'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(167,12): error TS2339: Property '_colorOffset' does not exist on type 'Spectrum'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(178,24): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. @@ -3533,15 +3598,13 @@ node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(200,24) node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(200,45): error TS2339: Property 'y' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(200,54): error TS2339: Property '_colorOffset' does not exist on type 'Spectrum'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(217,25): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(221,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(241,27): error TS2339: Property 'focus' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(251,13): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(251,39): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. -node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(253,23): error TS2345: Argument of type '{ opacity: number; }[]' is not assignable to parameter of type 'PropertyIndexedKeyframes | Keyframe[]'. - Type '{ opacity: number; }[]' is not assignable to type 'Keyframe[]'. - Type '{ opacity: number; }' is not assignable to type 'Keyframe'. - Property 'alignContent' is missing in type '{ opacity: number; }'. +node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(253,24): error TS2322: Type '{ opacity: number; }' is not assignable to type 'string | string[] | Keyframe'. + Type '{ opacity: number; }' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(253,38): error TS2322: Type '{ opacity: number; }' is not assignable to type 'string | string[] | Keyframe'. + Type '{ opacity: number; }' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(254,13): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(259,36): error TS2694: Namespace 'ColorPicker.Spectrum' has no exported member 'Palette'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(272,22): error TS2339: Property '__mutable' does not exist on type 'Element'. @@ -3600,14 +3663,6 @@ node_modules/chrome-devtools-frontend/front_end/common/Color.js(149,13): error T node_modules/chrome-devtools-frontend/front_end/common/Color.js(182,15): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(217,15): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(235,58): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(320,58): error TS2339: Property '_tmpHSLA' does not exist on type '(hsva: number[], out_rgba: number[]) => void'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(321,49): error TS2339: Property '_tmpHSLA' does not exist on type '(hsva: number[], out_rgba: number[]) => void'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(323,48): error TS2339: Property '_tmpHSLA' does not exist on type '(hsva: number[], out_rgba: number[]) => void'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(324,30): error TS2339: Property '_tmpHSLA' does not exist on type '(hsva: number[], out_rgba: number[]) => void'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(369,82): error TS2339: Property '_blendedFg' does not exist on type '(fgRGBA: number[], bgRGBA: number[]) => number'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(371,82): error TS2339: Property '_blendedFg' does not exist on type '(fgRGBA: number[], bgRGBA: number[]) => number'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(375,61): error TS2339: Property '_blendedFg' does not exist on type '(fgRGBA: number[], bgRGBA: number[]) => number'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(376,43): error TS2339: Property '_blendedFg' does not exist on type '(fgRGBA: number[], bgRGBA: number[]) => number'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(563,23): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(566,23): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(573,23): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. @@ -3620,11 +3675,8 @@ node_modules/chrome-devtools-frontend/front_end/common/Color.js(640,23): error T node_modules/chrome-devtools-frontend/front_end/common/Color.js(641,20): error TS2339: Property '_rgbaToNickname' does not exist on type 'typeof Color'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(646,22): error TS2339: Property '_rgbaToNickname' does not exist on type 'typeof Color'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(650,25): error TS2339: Property '_rgbaToNickname' does not exist on type 'typeof Color'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(661,5): error TS2322: Type '{ r: number; g: number; b: number; }' is not assignable to type '{ r: number; g: number; b: number; a: number; }'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(661,5): error TS2322: Type '{ r: number; g: number; b: number; }' is not assignable to type '{ r: number; g: number; b: number; a: number; }'. Property 'a' is missing in type '{ r: number; g: number; b: number; }'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(718,24): error TS2339: Property '_tmpHSLA' does not exist on type '(hsva: number[], out_rgba: number[]) => void'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(721,37): error TS2339: Property '_blendedFg' does not exist on type '(fgRGBA: number[], bgRGBA: number[]) => number'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(934,23): error TS2339: Property 'hashCode' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(935,45): error TS2345: Argument of type 'number | { min: number; max: number; }' is not assignable to parameter of type 'number | { min: number; max: number; count: number; }'. Type '{ min: number; max: number; }' is not assignable to type 'number | { min: number; max: number; count: number; }'. @@ -3678,9 +3730,8 @@ node_modules/chrome-devtools-frontend/front_end/common/Settings.js(277,41): erro node_modules/chrome-devtools-frontend/front_end/common/Settings.js(281,31): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/common/Settings.js(285,44): error TS2345: Argument of type 'string' is not assignable to parameter of type 'symbol'. node_modules/chrome-devtools-frontend/front_end/common/Settings.js(350,49): error TS2345: Argument of type 'string' is not assignable to parameter of type 'symbol'. -node_modules/chrome-devtools-frontend/front_end/common/Settings.js(424,21): error TS2345: Argument of type '{ pattern: string; }[]' is not assignable to parameter of type '{ pattern: string; disabled: boolean; }[]'. - Type '{ pattern: string; }' is not assignable to type '{ pattern: string; disabled: boolean; }'. - Property 'disabled' is missing in type '{ pattern: string; }'. +node_modules/chrome-devtools-frontend/front_end/common/Settings.js(424,22): error TS2322: Type '{ pattern: string; }' is not assignable to type '{ pattern: string; disabled: boolean; }'. + Property 'disabled' is missing in type '{ pattern: string; }'. node_modules/chrome-devtools-frontend/front_end/common/Settings.js(534,18): error TS2339: Property 'vertical' does not exist on type '{}'. node_modules/chrome-devtools-frontend/front_end/common/Settings.js(535,18): error TS2339: Property 'vertical' does not exist on type '{}'. node_modules/chrome-devtools-frontend/front_end/common/Settings.js(541,18): error TS2339: Property 'horizontal' does not exist on type '{}'. @@ -3755,9 +3806,6 @@ node_modules/chrome-devtools-frontend/front_end/components/DockController.js(70, node_modules/chrome-devtools-frontend/front_end/components/DockController.js(70,76): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/components/DockController.js(71,7): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/components/DockController.js(116,33): error TS2339: Property 'deepActiveElement' does not exist on type 'Document'. -node_modules/chrome-devtools-frontend/front_end/components/DockController.js(193,5): error TS2322: Type 'ToolbarButton' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarButton'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(62,24): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(125,94): error TS2339: Property 'remove' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(127,41): error TS2339: Property 'remove' does not exist on type 'Map'. @@ -3772,7 +3820,6 @@ node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(390,12): node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(392,12): error TS2339: Property 'href' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(418,10): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(432,31): error TS2339: Property 'createChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(440,43): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(443,16): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(445,16): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(481,27): error TS2694: Namespace 'Components' has no exported member '_LinkInfo'. @@ -3794,7 +3841,6 @@ node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(565,16): node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(572,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(580,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(587,16): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(616,5): error TS2322: Type '({ section: string; title: any; handler: () => void; } | { section: string; title: string; handler: any; })[]' is not assignable to type '{ title: string; handler: () => any; }[]'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(666,22): error TS2551: Property 'LinkHandler' does not exist on type 'typeof Linkifier'. Did you mean '_linkHandlers'? node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(668,47): error TS2694: Namespace 'Components.Linkifier' has no exported member 'LinkHandler'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(675,1): error TS8022: JSDoc '@extends' is not attached to a class. @@ -3809,9 +3855,12 @@ node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(732,19): node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(739,30): error TS2339: Property 'value' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(748,46): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(8,9): error TS2339: Property 'ConsoleContextSelector' does not exist on type '{ new (): Console; prototype: Console; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(45,5): error TS2322: Type 'ToolbarItem' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarItem'. +node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(36,55): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'ConsoleContextSelector' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(runtimeModel: RuntimeModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'runtimeModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'RuntimeModel'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(162,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(170,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(192,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -3892,8 +3941,9 @@ node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(107,9) node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(111,9): error TS2339: Property 'ConsoleSidebar' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(119,47): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(122,25): error TS2345: Argument of type 'Element' is not assignable to parameter of type 'Icon'. + Property 'createdCallback' is missing in type 'Element'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(133,9): error TS2339: Property 'ConsoleSidebar' does not exist on type '{ new (): Console; prototype: Console; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(147,26): error TS2345: Argument of type 'Element[]' is not assignable to parameter of type 'Icon[]'. +node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(147,27): error TS2322: Type 'Element' is not assignable to type 'Icon'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(177,60): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(179,61): error TS2339: Property 'ConsoleSidebar' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(209,41): error TS2339: Property 'asParsedURL' does not exist on type 'string'. @@ -3925,23 +3975,10 @@ node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(42,41): e node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(45,33): error TS2339: Property 'ConsoleSidebar' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(46,44): error TS2339: Property 'ConsoleSidebar' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(48,32): error TS2339: Property 'ConsoleViewFilter' does not exist on type '{ new (): Console; prototype: Console; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(63,33): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(88,44): error TS2694: Namespace 'Console.ConsoleView' has no exported member 'RegexMatchRange'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(92,48): error TS2339: Property 'ConsoleContextSelector' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(98,67): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(102,87): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(104,31): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(111,31): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(112,31): error TS2345: Argument of type 'ToolbarItem' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarItem'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(114,31): error TS2345: Argument of type 'ToolbarText' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarText' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(116,31): error TS2345: Argument of type 'ToolbarSettingToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(119,53): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(120,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(123,9): error TS2555: Expected at least 2 arguments, but got 1. @@ -3949,20 +3986,6 @@ node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(126,9): e node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(127,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(129,58): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(130,9): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(141,43): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(142,43): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(143,43): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(145,45): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(149,44): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(150,44): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(151,44): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(157,34): error TS2339: Property 'ConsoleViewport' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(169,30): error TS2339: Property 'ConsoleGroup' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(185,56): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. @@ -4002,6 +4025,7 @@ node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(674,42): node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(675,22): error TS2339: Property 'hasSelection' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(677,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(683,11): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(691,25): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(692,27): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(696,32): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleView.js(757,22): error TS2339: Property 'window' does not exist on type 'Element'. @@ -4165,7 +4189,6 @@ node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(14 node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1430,15): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1431,15): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1433,33): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1435,39): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1435,76): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1437,55): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1453,26): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. @@ -4286,9 +4309,6 @@ node_modules/chrome-devtools-frontend/front_end/console_counters/WarningErrorCou node_modules/chrome-devtools-frontend/front_end/console_counters/WarningErrorCounter.js(42,21): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/console_counters/WarningErrorCounter.js(58,5): error TS2322: Type 'number' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/console_counters/WarningErrorCounter.js(84,19): error TS2339: Property 'title' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/console_counters/WarningErrorCounter.js(96,5): error TS2322: Type 'ToolbarItem' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarItem'. node_modules/chrome-devtools-frontend/front_end/console_model/ConsoleModel.js(173,9): error TS2339: Property '_pageLoadSequenceNumber' does not exist on type 'ConsoleMessage'. node_modules/chrome-devtools-frontend/front_end/console_model/ConsoleModel.js(193,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/console_model/ConsoleModel.js(196,70): error TS2694: Namespace 'Protocol' has no exported member 'Log'. @@ -4353,9 +4373,8 @@ node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(65, node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(67,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(74,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(81,16): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(116,27): error TS2345: Argument of type '{ cookies: Cookie[]; }[]' is not assignable to parameter of type '{ folderName: string; cookies: Cookie[]; }[]'. - Type '{ cookies: Cookie[]; }' is not assignable to type '{ folderName: string; cookies: Cookie[]; }'. - Property 'folderName' is missing in type '{ cookies: Cookie[]; }'. +node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(116,28): error TS2322: Type '{ cookies: Cookie[]; }' is not assignable to type '{ folderName: string; cookies: Cookie[]; }'. + Property 'folderName' is missing in type '{ cookies: Cookie[]; }'. node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(320,33): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(320,52): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(346,21): error TS2555: Expected at least 2 arguments, but got 1. @@ -4391,7 +4410,6 @@ node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(19, node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(21,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(29,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(112,11): error TS2339: Property 'consume' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(201,24): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(206,18): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(208,18): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(210,18): error TS2555: Expected at least 2 arguments, but got 1. @@ -4412,7 +4430,6 @@ node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(170,31 node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(175,64): error TS2694: Namespace 'Coverage' has no exported member 'RangeUseCount'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(190,48): error TS2694: Namespace 'Coverage' has no exported member 'RangeUseCount'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(191,11): error TS2403: Subsequent variable declarations must have the same type. Variable 'entry' must be of type '[CSSStyleSheetHeader, any[]]', but here has type 'CoverageInfo'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(197,5): error TS2322: Type '[CSSStyleSheetHeader, any[]][]' is not assignable to type 'CoverageInfo[]'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(197,5): error TS2322: Type '[CSSStyleSheetHeader, any[]][]' is not assignable to type 'CoverageInfo[]'. Type '[CSSStyleSheetHeader, any[]]' is not assignable to type 'CoverageInfo'. Property '_contentProvider' is missing in type '[CSSStyleSheetHeader, any[]]'. @@ -4422,32 +4439,16 @@ node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(210,23 node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(214,21): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(230,25): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(250,31): error TS2694: Namespace 'Coverage' has no exported member 'RangeUseCount'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(251,24): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(267,37): error TS2339: Property 'peekLast' does not exist on type 'any[]'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(288,26): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(301,25): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(340,24): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(371,24): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(398,25): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(405,31): error TS2694: Namespace 'Coverage' has no exported member 'CoverageSegment'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(427,31): error TS2694: Namespace 'Coverage' has no exported member 'CoverageSegment'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(428,31): error TS2694: Namespace 'Coverage' has no exported member 'CoverageSegment'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(441,25): error TS2339: Property 'peekLast' does not exist on type '{ end: number; count: any; }[]'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(20,48): error TS2339: Property 'createChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(26,31): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(31,31): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(32,46): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(34,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(40,45): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(43,31): error TS2345: Argument of type 'ToolbarInput' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarInput' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(49,42): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(50,9): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(51,31): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(53,56): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(57,54): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(141,5): error TS2322: Type 'Timer' is not assignable to type 'number'. @@ -4459,6 +4460,9 @@ node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTes node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTestRunner.js(28,27): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTestRunner.js(52,31): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTestRunner.js(87,31): error TS2339: Property 'runtime' does not exist on type 'Window'. +node_modules/chrome-devtools-frontend/front_end/cpu_profiler_test_runner/ProfilerTestRunner.js(12,35): error TS2339: Property 'js_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/cpu_profiler_test_runner/ProfilerTestRunner.js(49,15): error TS2339: Property 'js_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/cpu_profiler_test_runner/ProfilerTestRunner.js(54,33): error TS2339: Property 'js_profiler' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(32,41): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(41,18): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(49,40): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -4518,7 +4522,6 @@ node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(472,24): e node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(474,27): error TS2339: Property 'isCreationNode' does not exist on type 'DataGridNode'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(591,44): error TS2345: Argument of type 'NODE_TYPE' is not assignable to parameter of type 'DataGridNode'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(595,25): error TS2339: Property 'data' does not exist on type 'NODE_TYPE'. -node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(622,5): error TS2322: Type 'DataGridNode[]' is not assignable to type 'NODE_TYPE[]'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(622,5): error TS2322: Type 'DataGridNode[]' is not assignable to type 'NODE_TYPE[]'. Type 'DataGridNode' is not assignable to type 'NODE_TYPE'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(641,56): error TS2339: Property 'offsetWidth' does not exist on type 'Element'. @@ -4697,7 +4700,6 @@ node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(2008,1): e node_modules/chrome-devtools-frontend/front_end/data_grid/ShowMoreDataGridNode.js(109,14): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/data_grid/SortableDataGrid.js(9,1): error TS8022: JSDoc '@extends' is not attached to a class. node_modules/chrome-devtools-frontend/front_end/data_grid/SortableDataGrid.js(11,40): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. -node_modules/chrome-devtools-frontend/front_end/data_grid/SortableDataGrid.js(19,5): error TS2322: Type '(a: SortableDataGridNode, b: SortableDataGridNode) => number' is not assignable to type '(arg0: NODE_TYPE, arg1: NODE_TYPE) => number'. node_modules/chrome-devtools-frontend/front_end/data_grid/SortableDataGrid.js(19,5): error TS2322: Type '(a: SortableDataGridNode, b: SortableDataGridNode) => number' is not assignable to type '(arg0: NODE_TYPE, arg1: NODE_TYPE) => number'. Types of parameters 'a' and 'arg0' are incompatible. Type 'NODE_TYPE' is not assignable to type 'SortableDataGridNode'. @@ -4735,10 +4737,8 @@ node_modules/chrome-devtools-frontend/front_end/data_grid/ViewportDataGrid.js(25 node_modules/chrome-devtools-frontend/front_end/data_grid/ViewportDataGrid.js(257,47): error TS2339: Property 'offsetHeight' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/data_grid/ViewportDataGrid.js(272,1): error TS8022: JSDoc '@extends' is not attached to a class. node_modules/chrome-devtools-frontend/front_end/data_grid/ViewportDataGrid.js(320,22): error TS2352: Conversion of type 'NODE_TYPE' to type 'ViewportDataGridNode' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. -node_modules/chrome-devtools-frontend/front_end/data_grid/ViewportDataGrid.js(334,9): error TS2322: Type 'NODE_TYPE[][]' is not assignable to type 'ViewportDataGridNode[][]'. -node_modules/chrome-devtools-frontend/front_end/data_grid/ViewportDataGrid.js(334,9): error TS2322: Type 'NODE_TYPE[][]' is not assignable to type 'ViewportDataGridNode[][]'. - Type 'NODE_TYPE[]' is not assignable to type 'ViewportDataGridNode[]'. - Type 'NODE_TYPE' is not assignable to type 'ViewportDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/data_grid/ViewportDataGrid.js(334,21): error TS2322: Type 'NODE_TYPE[]' is not assignable to type 'ViewportDataGridNode[]'. + Type 'NODE_TYPE' is not assignable to type 'ViewportDataGridNode'. node_modules/chrome-devtools-frontend/front_end/data_grid/ViewportDataGrid.js(363,15): error TS2339: Property 'parent' does not exist on type 'NODE_TYPE'. node_modules/chrome-devtools-frontend/front_end/data_grid/ViewportDataGrid.js(372,11): error TS2339: Property 'remove' does not exist on type 'NODE_TYPE'. node_modules/chrome-devtools-frontend/front_end/data_grid/ViewportDataGrid.js(373,11): error TS2339: Property 'parent' does not exist on type 'NODE_TYPE'. @@ -4808,9 +4808,6 @@ node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(279,45): node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(280,60): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(283,88): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(285,36): error TS2694: Namespace 'Adb' has no exported member 'PortForwardingRule'. -node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(286,5): error TS2322: Type 'ListWidget' is not assignable to type '{ renderItem(item: T, editable: boolean): Element; removeItemRequested(item: T, index: number): void; beginEdit(item: T): Editor; commitEdit(item: T, editor: Editor, isNew: boolean): void; } & { ...; }'. - Type 'ListWidget' is not assignable to type '{ renderItem(item: T, editable: boolean): Element; removeItemRequested(item: T, index: number): void; beginEdit(item: T): Editor; commitEdit(item: T, editor: Editor, isNew: boolean): void; }'. - Property 'renderItem' is missing in type 'ListWidget'. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(290,31): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(293,43): error TS2694: Namespace 'Adb' has no exported member 'PortForwardingRule'. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(297,29): error TS2555: Expected at least 2 arguments, but got 1. @@ -4837,9 +4834,6 @@ node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(461,11): node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(463,26): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(466,64): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(469,36): error TS2694: Namespace 'Adb' has no exported member 'PortForwardingRule'. -node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(470,5): error TS2322: Type 'ListWidget' is not assignable to type '{ renderItem(item: T, editable: boolean): Element; removeItemRequested(item: T, index: number): void; beginEdit(item: T): Editor; commitEdit(item: T, editor: Editor, isNew: boolean): void; } & { ...; }'. - Type 'ListWidget' is not assignable to type '{ renderItem(item: T, editable: boolean): Element; removeItemRequested(item: T, index: number): void; beginEdit(item: T): Editor; commitEdit(item: T, editor: Editor, isNew: boolean): void; }'. - Property 'renderItem' is missing in type 'ListWidget'. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(475,24): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(475,70): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(478,43): error TS2694: Namespace 'Adb' has no exported member 'PortForwardingRule'. @@ -4886,8 +4880,6 @@ node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(745,44): node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(783,36): error TS2694: Namespace 'Devices.DevicesView' has no exported member 'PageSection'. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(788,28): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(790,39): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(794,31): error TS2345: Argument of type 'ToolbarMenuButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(797,23): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(805,47): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/devices/DevicesView.js(806,47): error TS2555: Expected at least 2 arguments, but got 1. @@ -4935,9 +4927,8 @@ node_modules/chrome-devtools-frontend/front_end/devtools_compatibility.js(1290,2 node_modules/chrome-devtools-frontend/front_end/devtools_compatibility.js(1292,31): error TS2339: Property '__originalDOMTokenListToggle' does not exist on type 'DOMTokenList'. node_modules/chrome-devtools-frontend/front_end/devtools_compatibility.js(1293,28): error TS2339: Property '__originalDOMTokenListToggle' does not exist on type 'DOMTokenList'. node_modules/chrome-devtools-frontend/front_end/devtools_compatibility.js(1302,19): error TS2339: Property '__originalDOMTokenListToggle' does not exist on type 'DOMTokenList'. -node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(22,21): error TS2694: Namespace 'Diff' has no exported member 'Diff'. -node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(43,20): error TS2694: Namespace 'Diff' has no exported member 'Diff'. -node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(91,33): error TS2694: Namespace 'Diff' has no exported member 'Diff'. +node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(22,26): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. +node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(43,25): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,116): error TS2322: Type 'string[]' is not assignable to type '{ chars1: string; chars2: string; lineArray: string[]; }'. Property 'chars1' is missing in type 'string[]'. node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,240): error TS2322: Type '0' is not assignable to type '{ chars1: string; chars2: string; lineArray: string[]; }'. @@ -5131,9 +5122,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/ClassesPaneWidget.js(13 node_modules/chrome-devtools-frontend/front_end/elements/ClassesPaneWidget.js(152,32): error TS2339: Property 'checked' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/elements/ClassesPaneWidget.js(203,36): error TS2339: Property 'valuesArray' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/elements/ClassesPaneWidget.js(241,41): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/elements/ClassesPaneWidget.js(257,5): error TS2322: Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarToggle'. node_modules/chrome-devtools-frontend/front_end/elements/ClassesPaneWidget.js(291,94): error TS2339: Property 'addAll' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/elements/ClassesPaneWidget.js(297,55): error TS2339: Property 'addAll' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/elements/ClassesPaneWidget.js(299,57): error TS2339: Property 'valuesArray' does not exist on type 'Set'. @@ -5162,33 +5150,30 @@ node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleModel.js(3 node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleModel.js(65,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleModel.js(73,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleModel.js(84,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleModel.js(122,5): error TS2322: Type 'Promise>' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleModel.js(122,5): error TS2322: Type 'Promise>' is not assignable to type 'Promise'. Type 'Map' is not assignable to type 'ComputedStyle'. Property 'node' is missing in type 'Map'. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(48,36): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(51,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(52,49): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(57,31): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(58,71): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(73,12): error TS2339: Property '_filterRegex' does not exist on type 'ComputedStyleWidget'. -node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(91,24): error TS2345: Argument of type '(Promise | Promise)[]' is not assignable to parameter of type 'Iterable>'. +node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(91,24): error TS2345: Argument of type '(Promise | Promise)[]' is not assignable to parameter of type 'Iterable>'. Types of property '[Symbol.iterator]' are incompatible. - Type '() => IterableIterator | Promise>' is not assignable to type '() => Iterator>'. - Type 'IterableIterator | Promise>' is not assignable to type 'Iterator>'. + Type '() => IterableIterator | Promise>' is not assignable to type '() => Iterator>'. + Type 'IterableIterator | Promise>' is not assignable to type 'Iterator>'. Types of property 'next' are incompatible. - Type '{ (value?: any): IteratorResult | Promise>; (value?: any): IteratorResult | Promise>; }' is not assignable to type '{ (value?: any): IteratorResult>; (value?: any): IteratorResult>; }'. - Type 'IteratorResult | Promise>' is not assignable to type 'IteratorResult>'. - Type 'Promise | Promise' is not assignable to type 'CSSMatchedStyles | PromiseLike'. - Type 'Promise' is not assignable to type 'CSSMatchedStyles | PromiseLike'. - Type 'Promise' is not assignable to type 'PromiseLike'. + Type '{ (value?: any): IteratorResult | Promise>; (value?: any): IteratorResult | Promise>; }' is not assignable to type '{ (value?: any): IteratorResult>; (value?: any): IteratorResult>; }'. + Type 'IteratorResult | Promise>' is not assignable to type 'IteratorResult>'. + Type 'Promise | Promise' is not assignable to type 'ComputedStyle | PromiseLike'. + Type 'Promise' is not assignable to type 'ComputedStyle | PromiseLike'. + Type 'Promise' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. - Type '(onfulfilled?: (value: ComputedStyle) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise' is not assignable to type '(onfulfilled?: (value: CSSMatchedStyles) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => PromiseLike<...>'. + Type '(onfulfilled?: (value: CSSMatchedStyles) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise<...>' is not assignable to type '(onfulfilled?: (value: ComputedStyle) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => PromiseLike'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. - Type 'ComputedStyle' is not assignable to type 'CSSMatchedStyles'. - Property '_cssModel' is missing in type 'ComputedStyle'. + Type 'CSSMatchedStyles' is not assignable to type 'ComputedStyle'. + Property 'computedStyle' is missing in type 'CSSMatchedStyles'. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(147,52): error TS2339: Property 'keysArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(179,50): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ComputedStyleWidget.js(200,74): error TS2339: Property 'consume' does not exist on type 'Event'. @@ -5211,18 +5196,20 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementStatePaneWidget. node_modules/chrome-devtools-frontend/front_end/elements/ElementStatePaneWidget.js(51,16): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementStatePaneWidget.js(108,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/ElementStatePaneWidget.js(109,26): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/elements/ElementStatePaneWidget.js(124,5): error TS2322: Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarToggle'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsBreadcrumbs.js(12,46): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsBreadcrumbs.js(86,37): error TS2339: Property 'nextSiblingElement' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsBreadcrumbs.js(104,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/ElementsBreadcrumbs.js(215,38): error TS2339: Property 'offsetWidth' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsPanel.js(49,41): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/elements/ElementsPanel.js(83,51): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'ElementsPanel' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(domModel: DOMModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'domModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'DOMModel'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsPanel.js(90,32): error TS2339: Property 'addEventListener' does not exist on type 'typeof extensionServer'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsPanel.js(98,57): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsPanel.js(116,5): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsPanel.js(116,5): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. +node_modules/chrome-devtools-frontend/front_end/elements/ElementsPanel.js(116,5): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ...; }, insertBefore?: { ...'. Property 'appendApplicableItems' is missing in type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsPanel.js(159,24): error TS2339: Property 'remove' does not exist on type 'ElementsTreeOutline[]'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsPanel.js(180,12): error TS2339: Property 'removeChildren' does not exist on type 'Element'. @@ -5335,6 +5322,7 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(733,26): error TS2339: Property 'getComponentSelection' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(762,13): error TS2339: Property 'style' does not exist on type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(763,7): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. + Property 'after' is missing in type 'Node'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(767,32): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(772,10): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(796,24): error TS2339: Property 'setMultilineEditing' does not exist on type 'TreeOutline'. @@ -5351,7 +5339,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(855,24): error TS2339: Property 'keyCode' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(855,79): error TS2339: Property 'key' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(856,15): error TS2339: Property 'consume' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(868,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(878,19): error TS2339: Property 'runPendingUpdates' does not exist on type 'TreeOutline'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(972,37): error TS2339: Property 'selectNodeAfterEdit' does not exist on type 'TreeOutline'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(1106,27): error TS2339: Property '_decoratorExtensions' does not exist on type 'TreeOutline'. @@ -5388,7 +5375,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(1528,37): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(1533,40): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(1537,18): error TS2339: Property 'createTextChild' does not exist on type 'DocumentFragment'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(1577,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElementHighlighter.js(24,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(34,32): error TS2417: Class static side 'typeof ElementsTreeOutline' incorrectly extends base class static side 'typeof TreeOutline'. Types of property 'Events' are incompatible. @@ -5404,7 +5390,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(173,11): error TS2339: Property 'handled' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(197,11): error TS2339: Property 'handled' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(254,11): error TS2339: Property 'handled' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(270,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(271,26): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(495,29): error TS2339: Property 'totalOffsetLeft' does not exist on type 'HTMLElement'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(515,19): error TS2694: Namespace 'UI' has no exported member 'PopoverRequest'. @@ -5417,11 +5402,13 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(566,29): error TS2339: Property 'naturalHeight' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(567,26): error TS2339: Property 'currentSrc' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(594,19): error TS2339: Property 'hovered' does not exist on type 'TreeElement'. +node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(608,30): error TS2345: Argument of type '{ mode: string; showInfo: boolean; }' is not assignable to parameter of type '{ mode: string; showInfo: boolean; selectors: string; }'. + Property 'selectors' is missing in type '{ mode: string; showInfo: boolean; }'. +node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(614,22): error TS2345: Argument of type '{ mode: string; showInfo: boolean; }' is not assignable to parameter of type '{ mode: string; showInfo: boolean; selectors: string; }'. + Property 'selectors' is missing in type '{ mode: string; showInfo: boolean; }'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(755,33): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(758,36): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(813,22): error TS2339: Property 'index' does not exist on type 'DOMNode'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(847,24): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(920,9): error TS2322: Type 'Node & ParentNode' is not assignable to type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(920,9): error TS2322: Type 'Node & ParentNode' is not assignable to type 'Element'. Property 'assignedSlot' is missing in type 'Node & ParentNode'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(930,13): error TS2339: Property 'type' does not exist on type 'Element'. @@ -5468,7 +5455,12 @@ node_modules/chrome-devtools-frontend/front_end/elements/EventListenersWidget.js node_modules/chrome-devtools-frontend/front_end/elements/EventListenersWidget.js(73,15): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/EventListenersWidget.js(77,46): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/EventListenersWidget.js(129,52): error TS2339: Property 'value' does not exist on type 'EventTarget'. -node_modules/chrome-devtools-frontend/front_end/elements/InspectElementModeController.js(52,5): error TS2554: Expected 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/elements/InspectElementModeController.js(40,55): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'InspectElementModeController' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(overlayModel: OverlayModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'overlayModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'OverlayModel'. node_modules/chrome-devtools-frontend/front_end/elements/InspectElementModeController.js(91,24): error TS2694: Namespace 'Protocol' has no exported member 'Overlay'. node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(56,27): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(82,24): error TS2345: Argument of type '(Promise> | Promise)[]' is not assignable to parameter of type 'Iterable | PromiseLike>>'. @@ -5530,10 +5522,12 @@ node_modules/chrome-devtools-frontend/front_end/elements/PropertiesWidget.js(153 node_modules/chrome-devtools-frontend/front_end/elements/PropertiesWidget.js(162,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(29,25): error TS2339: Property 'property' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(43,42): error TS2339: Property 'scrollIntoViewIfNeeded' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(45,9): error TS2345: Argument of type '{ offset: number; backgroundColor: string; }[]' is not assignable to parameter of type 'PropertyIndexedKeyframes | Keyframe[]'. - Type '{ offset: number; backgroundColor: string; }[]' is not assignable to type 'Keyframe[]'. - Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'Keyframe'. - Property 'alignContent' is missing in type '{ offset: number; backgroundColor: string; }'. +node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(46,11): error TS2322: Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string | string[] | Keyframe'. + Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(47,11): error TS2322: Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string | string[] | Keyframe'. + Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(47,69): error TS2322: Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string | string[] | Keyframe'. + Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(35,18): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(50,51): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(69,32): error TS2339: Property '_instance' does not exist on type 'typeof StylesSidebarPane'. @@ -5599,12 +5593,8 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(95 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(957,30): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(962,44): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(964,29): error TS2339: Property 'tabIndex' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(970,40): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(972,43): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(973,24): error TS2339: Property 'tabIndex' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(974,38): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1019,61): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1021,51): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1022,35): error TS2339: Property 'selectorText' does not exist on type 'CSSRule'. @@ -5617,6 +5607,7 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(10 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1074,29): error TS2339: Property '_section' does not exist on type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1075,7): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1087,7): error TS2322: Type 'Node' is not assignable to type 'Element'. + Property 'assignedSlot' is missing in type 'Node'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1088,38): error TS2339: Property '_section' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1090,36): error TS2339: Property '_section' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1099,7): error TS2322: Type 'Node' is not assignable to type 'Element'. @@ -5756,24 +5747,33 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(29 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3021,19): error TS2339: Property 'key' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3049,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3120,39): error TS2694: Namespace 'UI.SuggestBox' has no exported member 'Suggestions'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3244,39): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3265,15): error TS2339: Property 'createTextChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3272,15): error TS2339: Property 'createTextChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3282,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3302,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3305,32): error TS2339: Property '_instance' does not exist on type 'typeof StylesSidebarPane'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3312,32): error TS2339: Property '_instance' does not exist on type 'typeof StylesSidebarPane'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3320,5): error TS2322: Type 'ToolbarButton' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarButton'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/EditDOMTestRunner.js(15,5): error TS2304: Cannot find name 'eventSender'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/EditDOMTestRunner.js(19,37): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(112,55): error TS2339: Property 'eventListener' does not exist on type 'TreeElement'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(128,20): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(132,20): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(191,20): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(316,20): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(322,13): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(326,33): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(372,22): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(384,33): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(429,28): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(490,15): error TS2339: Property 'runtime' does not exist on type 'Window'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(549,33): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(735,11): error TS2540: Cannot assign to 'name' because it is a constant or a read-only property. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(1024,26): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(1048,13): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(1052,13): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(1080,35): error TS2339: Property 'AnimationTimeline' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/StylesUpdateLinksTestRunner.js(99,35): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/StylesUpdateLinksTestRunner.js(119,31): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/emulation/AdvancedApp.js(56,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/emulation/AdvancedApp.js(92,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/emulation/AdvancedApp.js(105,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -5785,6 +5785,12 @@ node_modules/chrome-devtools-frontend/front_end/emulation/AdvancedApp.js(199,5): Property '_rootSplitWidget' does not exist on type '{ presentUI(document: Document): void; }'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeModel.js(9,1): error TS8022: JSDoc '@extends' is not attached to a class. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeModel.js(56,42): error TS2694: Namespace 'Emulation.EmulatedDevice' has no exported member 'Mode'. +node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeModel.js(67,57): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'DeviceModeModel' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(emulationModel: EmulationModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'emulationModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'EmulationModel'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeModel.js(75,34): error TS2365: Operator '>=' cannot be applied to types 'string' and 'number'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeModel.js(76,9): error TS2365: Operator '<=' cannot be applied to types 'string' and 'number'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeModel.js(86,59): error TS2365: Operator '>=' cannot be applied to types 'string' and 'number'. @@ -5802,8 +5808,6 @@ node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeModel.js(715 node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(25,74): error TS2694: Namespace 'Emulation.EmulatedDevice' has no exported member 'Mode'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(33,39): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(43,40): error TS2339: Property 'createChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(87,31): error TS2345: Argument of type 'ToolbarMenuButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(95,16): error TS2339: Property 'maxLength' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(96,16): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(96,24): error TS2555: Expected at least 2 arguments, but got 1. @@ -5811,21 +5815,9 @@ node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(1 node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(110,17): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(110,25): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(148,30): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(152,31): error TS2345: Argument of type 'ToolbarMenuButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(158,36): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(162,31): error TS2345: Argument of type 'ToolbarMenuButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(168,27): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(172,31): error TS2345: Argument of type 'ToolbarMenuButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(175,31): error TS2345: Argument of type 'ToolbarMenuButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(186,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(194,32): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(195,31): error TS2345: Argument of type 'ToolbarMenuButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(211,26): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(212,26): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(213,26): error TS2555: Expected at least 2 arguments, but got 1. @@ -5845,9 +5837,6 @@ node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(3 node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(302,71): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(303,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(305,44): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(338,5): error TS2322: Type 'ToolbarItem' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarItem'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(392,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(397,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeToolbar.js(441,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -5877,8 +5866,6 @@ node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(83,9 node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(84,7): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(84,34): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(84,63): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(103,12): error TS2339: Property '_model' does not exist on type 'typeof DeviceModeView'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(104,12): error TS2339: Property '_model' does not exist on type 'typeof DeviceModeView'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(105,9): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(132,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(143,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -5903,18 +5890,8 @@ node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(483, node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeView.js(500,22): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(18,22): error TS2339: Property 'singleton' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(33,24): error TS2694: Namespace 'Protocol' has no exported member 'Page'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(38,30): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(39,26): error TS2339: Property 'setNonEmulatedAvailableSize' does not exist on type 'typeof DeviceModeView'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(41,28): error TS2339: Property 'captureFullSizeScreenshot' does not exist on type 'typeof DeviceModeView'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(43,28): error TS2339: Property 'captureAreaScreenshot' does not exist on type 'typeof DeviceModeView'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(45,28): error TS2339: Property 'captureScreenshot' does not exist on type 'typeof DeviceModeView'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(50,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(53,37): error TS2694: Namespace 'Protocol' has no exported member 'Page'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(63,66): error TS2339: Property 'isShowing' does not exist on type 'typeof DeviceModeView'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(70,32): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(71,28): error TS2339: Property 'show' does not exist on type 'typeof DeviceModeView'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(73,64): error TS2339: Property 'element' does not exist on type 'typeof DeviceModeView'. -node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(76,30): error TS2339: Property 'detach' does not exist on type 'typeof DeviceModeView'. node_modules/chrome-devtools-frontend/front_end/emulation/DeviceModeWrapper.js(120,45): error TS2694: Namespace 'Protocol' has no exported member 'Page'. node_modules/chrome-devtools-frontend/front_end/emulation/DevicesSettingsTab.js(15,31): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/emulation/DevicesSettingsTab.js(16,46): error TS2555: Expected at least 2 arguments, but got 1. @@ -5948,6 +5925,12 @@ node_modules/chrome-devtools-frontend/front_end/emulation/EmulatedDevices.js(470 node_modules/chrome-devtools-frontend/front_end/emulation/InspectedPagePlaceholder.js(21,20): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/emulation/InspectedPagePlaceholder.js(22,35): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/emulation/InspectedPagePlaceholder.js(72,15): error TS2339: Property 'singleton' does not exist on type 'Window'. +node_modules/chrome-devtools-frontend/front_end/emulation/MediaQueryInspector.js(25,51): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'MediaQueryInspector' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(cssModel: CSSModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'cssModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'CSSModel'. node_modules/chrome-devtools-frontend/front_end/emulation/MediaQueryInspector.js(74,41): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/emulation/MediaQueryInspector.js(101,41): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/emulation/MediaQueryInspector.js(111,31): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. @@ -6072,60 +6055,22 @@ node_modules/chrome-devtools-frontend/front_end/event_listeners/EventListenersVi node_modules/chrome-devtools-frontend/front_end/event_listeners/EventListenersView.js(301,29): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/event_listeners/EventListenersView.js(311,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/event_listeners/EventListenersView.js(321,13): error TS2339: Property 'consume' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(130,25): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(132,23): error TS2339: Property 'registerHandler' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(145,25): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(149,19): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(186,12): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(203,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(207,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(224,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(241,12): error TS2339: Property '__defineGetter__' does not exist on type 'Panels'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(243,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(249,53): error TS2339: Property 'nextObjectId' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(251,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(255,40): error TS2339: Property 'hasHandler' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(268,25): error TS2339: Property 'unregisterHandler' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(270,25): error TS2339: Property 'registerHandler' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(274,25): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(278,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(298,14): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(300,14): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(314,12): error TS8022: JSDoc '@extends' is not attached to a class. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(322,55): error TS2339: Property 'nextObjectId' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(327,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(371,12): error TS8022: JSDoc '@extends' is not attached to a class. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(381,12): error TS8022: JSDoc '@extends' is not attached to a class. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(391,12): error TS8022: JSDoc '@extends' is not attached to a class. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(401,44): error TS2339: Property 'nextObjectId' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(410,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(419,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(429,12): error TS8022: JSDoc '@extends' is not attached to a class. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(435,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(448,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(452,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(457,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(475,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(492,62): error TS2339: Property 'nextObjectId' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(493,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(515,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(529,12): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(544,12): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(551,12): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(569,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(586,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(597,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(623,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(627,23): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(662,21): error TS2339: Property 'sendRequest' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(678,10): error TS2339: Property 'registerHandler' does not exist on type 'ExtensionServerClient'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(678,43): error TS2551: Property '_onCallback' does not exist on type 'ExtensionServerClient'. Did you mean '_callbacks'? -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(682,49): error TS2339: Property '_onMessage' does not exist on type 'ExtensionServerClient'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(789,21): error TS2339: Property 'exposeWebInspectorNamespace' does not exist on type 'ExtensionDescriptor'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(790,12): error TS2339: Property 'webInspector' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionPanel.js(232,23): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionPanel.js(240,18): error TS2339: Property 'style' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionPanel.js(246,24): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionPanel.js(279,40): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionRegistryStub.js(30,13): error TS2339: Property 'InspectorExtensionRegistry' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(129,5): error TS2555: Expected at least 2 arguments, but got 1. @@ -6134,14 +6079,9 @@ node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(16 node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(219,43): error TS2694: Namespace 'Protocol' has no exported member 'Network'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(244,54): error TS2339: Property 'traverseNextNode' does not exist on type 'HTMLElement'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(245,27): error TS2693: 'ShadowRoot' only refers to a type, but is being used as a value here. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(290,77): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarButton'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(416,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(463,53): error TS2345: Argument of type '{ url: string; type: string; }' is not assignable to parameter of type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. Property 'contentURL' is missing in type '{ url: string; type: string; }'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(471,22): error TS2339: Property 'valuesArray' does not exist on type 'Map; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }>'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(502,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(542,14): error TS2339: Property '_extensionOrigin' does not exist on type 'MessagePort'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(567,30): error TS2339: Property 'KeyboardEvent' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(599,76): error TS2345: Argument of type 'symbol' is not assignable to parameter of type 'string'. @@ -6157,6 +6097,16 @@ node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(71 node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(765,31): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(777,31): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(839,43): error TS2694: Namespace 'Extensions.ExtensionStatus' has no exported member 'Record'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(881,30): error TS2339: Property 'resourceTreeModel' does not exist on type 'true | ResourceTreeFrame'. + Property 'resourceTreeModel' does not exist on type 'true'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(886,48): error TS2339: Property 'id' does not exist on type 'true | ResourceTreeFrame'. + Property 'id' does not exist on type 'true'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(891,113): error TS2339: Property 'url' does not exist on type 'true | ResourceTreeFrame'. + Property 'url' does not exist on type 'true'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(897,48): error TS2339: Property 'id' does not exist on type 'true | ResourceTreeFrame'. + Property 'id' does not exist on type 'true'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(901,44): error TS2339: Property 'url' does not exist on type 'true | ResourceTreeFrame'. + Property 'url' does not exist on type 'true'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(918,34): error TS2694: Namespace 'SDK.RuntimeModel' has no exported member 'EvaluationResult'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(976,45): error TS2694: Namespace 'Extensions.ExtensionStatus' has no exported member 'Record'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(983,59): error TS2339: Property 'vsprintf' does not exist on type 'StringConstructor'. @@ -6299,8 +6249,6 @@ node_modules/chrome-devtools-frontend/front_end/formatter_worker/ESTreeWalker.js Property 'start' is missing in type 'TemplateLiteralNode'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/ESTreeWalker.js(63,57): error TS2345: Argument of type 'TemplateLiteralNode' is not assignable to parameter of type 'Node'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/ESTreeWalker.js(65,66): error TS2345: Argument of type 'TemplateLiteralNode' is not assignable to parameter of type 'Node'. -node_modules/chrome-devtools-frontend/front_end/formatter_worker/ESTreeWalker.js(89,53): error TS2300: Duplicate identifier 'SkipSubtree'. -node_modules/chrome-devtools-frontend/front_end/formatter_worker/ESTreeWalker.js(90,30): error TS2300: Duplicate identifier 'SkipSubtree'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormattedContentBuilder.js(47,39): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormatterWorker.js(43,13): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormatterWorker.js(44,24): error TS2339: Property 'token' does not exist on type 'void'. @@ -6476,6 +6424,13 @@ node_modules/chrome-devtools-frontend/front_end/formatter_worker.js(5,11): error node_modules/chrome-devtools-frontend/front_end/formatter_worker.js(6,8): error TS2339: Property 'importScripts' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/har_importer/HARImporter.js(26,11): error TS2403: Subsequent variable declarations must have the same type. Variable 'page' must be of type 'any', but here has type 'HARPage'. node_modules/chrome-devtools-frontend/front_end/har_importer/HARImporter.js(46,5): error TS2322: Type 'Date' is not assignable to type 'number'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(320,70): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(321,35): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(366,55): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(590,24): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(624,20): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(653,15): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(658,33): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(678,36): error TS2339: Property 'instance' does not exist on type 'typeof SamplingHeapProfileType'. node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(682,36): error TS2339: Property 'instance' does not exist on type 'typeof SamplingHeapProfileType'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(37,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -6491,6 +6446,8 @@ node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapsho node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(918,34): error TS2345: Argument of type 'Uint32Array' is not assignable to parameter of type 'number[]'. Property 'pop' is missing in type 'Uint32Array'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(920,34): error TS2345: Argument of type 'Uint32Array' is not assignable to parameter of type 'number[]'. +node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1020,16): error TS2587: JSDoc type 'JSHeapSnapshotEdge' circularly references itself. +node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1028,16): error TS2587: JSDoc type 'JSHeapSnapshotRetainerEdge' circularly references itself. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1045,5): error TS2322: Type 'void' is not assignable to type 'HeapSnapshotNode'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1083,14): error TS2339: Property 'key' does not exist on type '(arg0: HeapSnapshotNode) => boolean'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1086,14): error TS2339: Property 'key' does not exist on type '(arg0: HeapSnapshotNode) => boolean'. @@ -6735,8 +6692,6 @@ node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowEditor.js node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowEditor.js(356,20): error TS2339: Property 'value' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowEditor.js(361,30): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowEditor.js(367,20): error TS2339: Property 'value' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowModel.js(46,38): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowModel.js(63,41): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(16,35): error TS2339: Property '_constructor' does not exist on type 'typeof ColorSwatch'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(17,32): error TS2339: Property '_constructor' does not exist on type 'typeof ColorSwatch'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(21,83): error TS2339: Property '_constructor' does not exist on type 'typeof ColorSwatch'. @@ -6755,7 +6710,6 @@ node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(210 node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(227,39): error TS2339: Property '_constructor' does not exist on type 'typeof CSSShadowSwatch'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(228,36): error TS2339: Property '_constructor' does not exist on type 'typeof CSSShadowSwatch'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(232,91): error TS2339: Property '_constructor' does not exist on type 'typeof CSSShadowSwatch'. -node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(248,39): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(290,10): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(291,33): error TS2339: Property 'createChild' does not exist on type 'CSSShadowSwatch'. node_modules/chrome-devtools-frontend/front_end/inline_editor/SwatchPopoverHelper.js(13,37): error TS2345: Argument of type 'symbol' is not assignable to parameter of type 'boolean'. @@ -6767,8 +6721,8 @@ node_modules/chrome-devtools-frontend/front_end/inline_editor/SwatchPopoverHelpe node_modules/chrome-devtools-frontend/front_end/inline_editor/SwatchPopoverHelper.js(111,15): error TS2339: Property 'key' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/inline_editor/SwatchPopoverHelper.js(113,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/integration_test_runner.js(5,10): error TS2339: Property 'testRunner' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/integration_test_runner.js(6,3): error TS2304: Cannot find name 'testRunner'. -node_modules/chrome-devtools-frontend/front_end/integration_test_runner.js(7,3): error TS2304: Cannot find name 'testRunner'. +node_modules/chrome-devtools-frontend/front_end/integration_test_runner.js(6,3): error TS2552: Cannot find name 'testRunner'. Did you mean 'TestRunner'? +node_modules/chrome-devtools-frontend/front_end/integration_test_runner.js(7,3): error TS2552: Cannot find name 'testRunner'. Did you mean 'TestRunner'? node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerDetailsView.js(43,44): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerDetailsView.js(84,15): error TS2339: Property 'which' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerDetailsView.js(95,24): error TS2694: Namespace 'Protocol' has no exported member 'LayerTree'. @@ -6828,12 +6782,12 @@ node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerTreeOutline.js node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerTreeOutline.js(199,80): error TS2339: Property '_layer' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerTreeOutline.js(222,11): error TS2339: Property 'createTextChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerTreeOutline.js(223,25): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. +node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(110,15): error TS2587: JSDoc type 'Layer' circularly references itself. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(125,84): error TS2339: Property 'scrollRectIndex' does not exist on type 'Selection'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(135,19): error TS2694: Namespace 'SDK' has no exported member 'SnapshotWithRect'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(149,34): error TS2339: Property '_snapshot' does not exist on type 'Selection'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(153,20): error TS2694: Namespace 'SDK' has no exported member 'SnapshotWithRect'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(231,9): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(235,7): error TS2554: Expected 3 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(44,30): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(44,46): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(54,47): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -6872,8 +6826,6 @@ node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(626 node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(641,21): error TS2339: Property 'clientX' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(642,22): error TS2339: Property 'clientY' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(670,22): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(672,31): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(693,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(697,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(708,15): error TS2339: Property 'which' does not exist on type 'Event'. @@ -6892,8 +6844,6 @@ node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(858 node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(861,81): error TS2339: Property 'image' does not exist on type 'WebGLTexture'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(928,26): error TS2694: Namespace 'SDK' has no exported member 'SnapshotWithRect'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(932,39): error TS2345: Argument of type 'any[][]' is not assignable to parameter of type 'ReadonlyArray<[any, any]>'. - Type 'any[]' is not assignable to type '[any, any]'. - Property '0' is missing in type 'any[]'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(1080,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(1098,15): error TS2304: Cannot find name 'CSSMatrix'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(1143,19): error TS2694: Namespace 'SDK' has no exported member 'SnapshotWithRect'. @@ -6911,7 +6861,6 @@ node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.j node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(85,39): error TS2551: Property '_logItemCategoriesMap' does not exist on type 'typeof PaintProfilerView'. Did you mean '_initLogItemCategories'? node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(86,44): error TS2551: Property '_logItemCategoriesMap' does not exist on type 'typeof PaintProfilerView'. Did you mean '_initLogItemCategories'? node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(128,35): error TS2551: Property '_logItemCategoriesMap' does not exist on type 'typeof PaintProfilerView'. Did you mean '_initLogItemCategories'? -node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(129,5): error TS2322: Type '{}' is not assignable to type '{ [x: string]: PaintProfilerCategory; }'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(129,5): error TS2322: Type '{}' is not assignable to type '{ [x: string]: PaintProfilerCategory; }'. Index signature is missing in type '{}'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(158,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. @@ -6929,14 +6878,8 @@ node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.j node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(19,22): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(20,20): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(35,48): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(39,51): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(40,51): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(44,51): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(48,44): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(50,49): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(128,18): error TS2339: Property 'focus' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(144,18): error TS2339: Property 'focus' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/TransformController.js(154,26): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. @@ -6980,6 +6923,7 @@ node_modules/chrome-devtools-frontend/front_end/layers/LayersPanel.js(150,22): e node_modules/chrome-devtools-frontend/front_end/layers/LayersPanel.js(160,58): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/layers/LayersPanel.js(169,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/layers/LayersPanel.js(187,22): error TS2694: Namespace 'Common' has no exported member 'Event'. +node_modules/chrome-devtools-frontend/front_end/layers_test_runner/LayersTestRunner.js(55,22): error TS2339: Property 'layers' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/layers_test_runner/LayersTestRunner.js(130,3): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/ExecutionContextSelector.js(63,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/main/ExecutionContextSelector.js(83,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -6992,12 +6936,6 @@ node_modules/chrome-devtools-frontend/front_end/main/Main.js(192,32): error TS25 node_modules/chrome-devtools-frontend/front_end/main/Main.js(193,32): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(194,32): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(195,32): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/main/Main.js(204,5): error TS2322: Type 'CSSWorkspaceBinding' is not assignable to type '{ rawLocationToUILocation(rawLocation: CSSLocation): UILocation; uiLocationToRawLocations(uiLocation: UILocation): CSSLocation[]; } & { rawLocationToUILocation(rawLocation: CSSLocation): UILocation; uiLocationToRawLocations(uiLocation: UILocation): CSSLocation[]; }'. - Type 'CSSWorkspaceBinding' is not assignable to type '{ rawLocationToUILocation(rawLocation: CSSLocation): UILocation; uiLocationToRawLocations(uiLocation: UILocation): CSSLocation[]; }'. -node_modules/chrome-devtools-frontend/front_end/main/Main.js(204,5): error TS2322: Type 'CSSWorkspaceBinding' is not assignable to type '{ rawLocationToUILocation(rawLocation: CSSLocation): UILocation; uiLocationToRawLocations(uiLocation: UILocation): CSSLocation[]; } & { rawLocationToUILocation(rawLocation: CSSLocation): UILocation; uiLocationToRawLocations(uiLocation: UILocation): CSSLocation[]; }'. - Type 'CSSWorkspaceBinding' is not assignable to type '{ rawLocationToUILocation(rawLocation: CSSLocation): UILocation; uiLocationToRawLocations(uiLocation: UILocation): CSSLocation[]; }'. - Property '_workspace' does not exist on type '{ rawLocationToUILocation(rawLocation: CSSLocation): UILocation; uiLocationToRawLocations(uiLocation: UILocation): CSSLocation[]; }'. -node_modules/chrome-devtools-frontend/front_end/main/Main.js(208,5): error TS2322: Type 'ExtensionServer' is not assignable to type 'typeof extensionServer'. node_modules/chrome-devtools-frontend/front_end/main/Main.js(208,5): error TS2322: Type 'ExtensionServer' is not assignable to type 'typeof extensionServer'. Property '_extensionAPITestHook' is missing in type 'ExtensionServer'. node_modules/chrome-devtools-frontend/front_end/main/Main.js(230,10): error TS2339: Property 'runtime' does not exist on type 'Window'. @@ -7024,23 +6962,12 @@ node_modules/chrome-devtools-frontend/front_end/main/Main.js(472,12): error TS23 node_modules/chrome-devtools-frontend/front_end/main/Main.js(473,12): error TS2339: Property 'inspectorAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/main/Main.js(567,65): error TS2339: Property 'deepActiveElement' does not exist on type 'Document'. node_modules/chrome-devtools-frontend/front_end/main/Main.js(591,25): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/main/Main.js(599,5): error TS2322: Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarMenuButton'. node_modules/chrome-devtools-frontend/front_end/main/Main.js(608,42): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/main/Main.js(609,34): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(616,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(617,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(618,40): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(619,39): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/main/Main.js(636,41): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/main/Main.js(637,41): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/main/Main.js(638,41): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/main/Main.js(639,41): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/main/Main.js(653,44): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(654,44): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(656,68): error TS2555: Expected at least 2 arguments, but got 1. @@ -7048,9 +6975,6 @@ node_modules/chrome-devtools-frontend/front_end/main/Main.js(657,27): error TS23 node_modules/chrome-devtools-frontend/front_end/main/Main.js(668,69): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(682,32): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/main/Main.js(685,27): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/main/Main.js(702,5): error TS2322: Type 'ToolbarItem' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarItem'. node_modules/chrome-devtools-frontend/front_end/main/Main.js(721,22): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(724,22): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/Main.js(727,22): error TS2555: Expected at least 2 arguments, but got 1. @@ -7082,6 +7006,7 @@ node_modules/chrome-devtools-frontend/front_end/main/RenderingOptions.js(52,25): node_modules/chrome-devtools-frontend/front_end/main/RenderingOptions.js(57,42): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/main/RenderingOptions.js(58,51): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/RenderingOptions.js(59,47): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/main/RequestAppBannerActionDelegate.js(18,14): error TS2339: Property 'pageAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/MobileThrottlingSelector.js(7,48): error TS2694: Namespace 'MobileThrottling' has no exported member 'MobileThrottlingConditionsGroup'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/MobileThrottlingSelector.js(7,100): error TS2694: Namespace 'MobileThrottling' has no exported member 'ConditionsList'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/MobileThrottlingSelector.js(17,34): error TS2694: Namespace 'MobileThrottling' has no exported member 'ConditionsList'. @@ -7099,10 +7024,15 @@ node_modules/chrome-devtools-frontend/front_end/mobile_throttling/NetworkThrottl node_modules/chrome-devtools-frontend/front_end/mobile_throttling/NetworkThrottlingSelector.js(37,32): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/NetworkThrottlingSelector.js(38,31): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/NetworkThrottlingSelector.js(43,62): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(11,34): error TS2694: Namespace 'MobileThrottling' has no exported member 'CPUThrottlingRates'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(16,59): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(18,36): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(20,36): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. +node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(28,57): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'ThrottlingManager' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(emulationModel: EmulationModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'emulationModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'EmulationModel'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(44,42): error TS2694: Namespace 'MobileThrottling' has no exported member 'NetworkThrottlingConditionsGroup'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(45,44): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(48,21): error TS2339: Property 'removeChildren' does not exist on type 'HTMLSelectElement'. @@ -7117,13 +7047,11 @@ node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingMana node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(141,81): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(147,42): error TS2694: Namespace 'MobileThrottling' has no exported member 'MobileThrottlingConditionsGroup'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(148,35): error TS2694: Namespace 'MobileThrottling' has no exported member 'ConditionsList'. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(178,32): error TS2694: Namespace 'MobileThrottling' has no exported member 'CPUThrottlingRates'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(188,20): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(218,82): error TS2339: Property 'selectedIndex' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(224,32): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(266,15): error TS2339: Property 'singleton' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(16,35): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(17,43): error TS2694: Namespace 'MobileThrottling' has no exported member 'CPUThrottlingRates'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(20,18): error TS2300: Duplicate identifier 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(22,30): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(25,16): error TS2555: Expected at least 2 arguments, but got 1. @@ -7146,7 +7074,6 @@ node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPres node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(77,38): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(82,38): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(87,39): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(94,37): error TS2694: Namespace 'MobileThrottling' has no exported member 'CPUThrottlingRates'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingSettingsTab.js(14,25): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingSettingsTab.js(14,68): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingSettingsTab.js(17,9): error TS2555: Expected at least 2 arguments, but got 1. @@ -7178,18 +7105,9 @@ node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingSett node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingSettingsTab.js(197,50): error TS2365: Operator '>=' cannot be applied to types 'string' and 'number'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingSettingsTab.js(197,64): error TS2365: Operator '<=' cannot be applied to types 'string' and 'number'. node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(18,32): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(19,37): error TS2345: Argument of type 'ToolbarCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarCheckbox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(21,42): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(23,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(24,44): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(26,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(28,51): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'BlockedPattern'. -node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(29,5): error TS2322: Type 'ListWidget' is not assignable to type '{ renderItem(item: T, editable: boolean): Element; removeItemRequested(item: T, index: number): void; beginEdit(item: T): Editor; commitEdit(item: T, editor: Editor, isNew: boolean): void; } & { ...; }'. - Type 'ListWidget' is not assignable to type '{ renderItem(item: T, editable: boolean): Element; removeItemRequested(item: T, index: number): void; beginEdit(item: T): Editor; commitEdit(item: T, editor: Editor, isNew: boolean): void; }'. - Property 'renderItem' is missing in type 'ListWidget'. node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(35,58): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'BlockedPattern'. node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(52,39): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/network/BlockedURLsPane.js(53,47): error TS2555: Expected at least 2 arguments, but got 1. @@ -7334,6 +7252,12 @@ node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(114,37 node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(124,26): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(144,44): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(147,50): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(152,57): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'NetworkLogView' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(networkManager: NetworkManager) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'networkManager' and 'model' are incompatible. + Type 'T' is not assignable to type 'NetworkManager'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(174,46): error TS2694: Namespace 'Protocol' has no exported member 'Network'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(175,46): error TS2694: Namespace 'Protocol' has no exported member 'Network'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(184,38): error TS2694: Namespace 'Network.NetworkLogView' has no exported member 'Filter'. @@ -7355,14 +7279,12 @@ node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(766,59 node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(780,45): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(853,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(867,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(905,5): error TS2322: Type 'ViewportDataGridNode[]' is not assignable to type 'NetworkNode[]'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(905,5): error TS2322: Type 'ViewportDataGridNode[]' is not assignable to type 'NetworkNode[]'. Type 'ViewportDataGridNode' is not assignable to type 'NetworkNode'. Property '_parentView' is missing in type 'ViewportDataGridNode'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(916,20): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(938,41): error TS2339: Property 'firstValue' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1074,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1149,5): error TS2554: Expected 3 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1150,69): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1157,13): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1162,13): error TS2555: Expected at least 2 arguments, but got 1. @@ -7383,6 +7305,7 @@ node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1194,9 node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1204,13): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1214,13): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1223,13): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1294,25): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1309,17): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1314,17): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogView.js(1501,39): error TS2694: Namespace 'Network.NetworkLogView' has no exported member 'Filter'. @@ -7474,42 +7397,18 @@ node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(67,53): node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(79,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(140,55): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(158,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(167,42): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(169,44): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(171,42): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(174,66): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(175,42): error TS2345: Argument of type 'ToolbarSettingToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(177,42): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(180,35): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(183,67): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(184,9): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(185,42): error TS2345: Argument of type 'ToolbarSettingToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(188,69): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(189,9): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(190,42): error TS2345: Argument of type 'ToolbarSettingToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(192,42): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(193,61): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(196,42): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(197,35): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(198,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(201,48): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(202,9): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(203,42): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(206,42): error TS2345: Argument of type 'ToolbarCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(207,42): error TS2345: Argument of type 'ToolbarComboBox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarComboBox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(209,42): error TS2345: Argument of type 'ToolbarItem' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(274,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(287,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(291,7): error TS2322: Type 'Timer' is not assignable to type 'number'. @@ -7518,8 +7417,6 @@ node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(397,22): node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(404,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(412,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(420,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(438,61): error TS2345: Argument of type 'ToolbarItem' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(520,46): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(523,22): error TS2339: Property 'isSelfOrDescendant' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/network/NetworkPanel.js(550,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -7533,7 +7430,6 @@ node_modules/chrome-devtools-frontend/front_end/network/NetworkTimeCalculator.js node_modules/chrome-devtools-frontend/front_end/network/NetworkTimeCalculator.js(219,7): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/network/NetworkTimeCalculator.js(243,27): error TS2339: Property 'secondsToString' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/network/NetworkTimeCalculator.js(247,30): error TS2339: Property 'secondsToString' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkTimeCalculator.js(252,7): error TS2322: Type '{ left: any; right: string; }' is not assignable to type '{ left: string; right: string; tooltip: string; }'. node_modules/chrome-devtools-frontend/front_end/network/NetworkTimeCalculator.js(252,7): error TS2322: Type '{ left: any; right: string; }' is not assignable to type '{ left: string; right: string; tooltip: string; }'. Property 'tooltip' is missing in type '{ left: any; right: string; }'. node_modules/chrome-devtools-frontend/front_end/network/NetworkTimeCalculator.js(255,26): error TS2339: Property 'secondsToString' does not exist on type 'NumberConstructor'. @@ -7672,13 +7568,7 @@ node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameVi node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(38,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(43,27): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(63,49): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(65,41): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(72,41): error TS2345: Argument of type 'ToolbarComboBox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarComboBox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(76,49): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(78,41): error TS2345: Argument of type 'ToolbarInput' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarInput' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(86,49): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(99,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(100,46): error TS2555: Expected at least 2 arguments, but got 1. @@ -7696,12 +7586,22 @@ node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameVi node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(241,34): error TS2694: Namespace 'SDK.NetworkRequest' has no exported member 'WebSocketFrame'. node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(250,14): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(251,14): error TS2339: Property 'title' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(292,5): error TS2322: Type 'StaticContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/network/ResourceWebSocketFrameView.js(292,5): error TS2322: Type 'StaticContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. Property '_contentURL' does not exist on type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/network_log/HAREntry.js(130,29): error TS2339: Property 'localizedFailDescription' does not exist on type 'NetworkRequest'. node_modules/chrome-devtools-frontend/front_end/network_log/HAREntry.js(150,36): error TS2694: Namespace 'NetworkLog.HAREntry' has no exported member 'Timing'. node_modules/chrome-devtools-frontend/front_end/network_log/HAREntry.js(319,21): error TS2339: Property 'Timing' does not exist on type 'typeof HAREntry'. +node_modules/chrome-devtools-frontend/front_end/network_log/NetworkLog.js(44,57): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'NetworkLog' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(networkManager: NetworkManager) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'networkManager' and 'model' are incompatible. + Type 'T' is not assignable to type 'NetworkManager'. +node_modules/chrome-devtools-frontend/front_end/network_log/NetworkLog.js(99,59): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. +node_modules/chrome-devtools-frontend/front_end/network_log/NetworkLog.js(101,61): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'NetworkLog' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(networkManager: NetworkManager) => void' is not assignable to type '(model: T) => void'. node_modules/chrome-devtools-frontend/front_end/network_log/NetworkLog.js(123,24): error TS2694: Namespace 'Protocol' has no exported member 'Network'. node_modules/chrome-devtools-frontend/front_end/network_log/NetworkLog.js(154,49): error TS2694: Namespace 'NetworkLog.NetworkLog' has no exported member '_InitiatorInfo'. node_modules/chrome-devtools-frontend/front_end/network_log/NetworkLog.js(165,38): error TS2694: Namespace 'NetworkLog.NetworkLog' has no exported member '_InitiatorInfo'. @@ -7735,15 +7635,15 @@ node_modules/chrome-devtools-frontend/front_end/network_priorities/NetworkPriori node_modules/chrome-devtools-frontend/front_end/network_priorities/NetworkPriorities.js(56,29): error TS2694: Namespace 'Protocol' has no exported member 'Network'. node_modules/chrome-devtools-frontend/front_end/network_priorities/NetworkPriorities.js(57,66): error TS2339: Property '_symbolicToNumericPriorityMap' does not exist on type '() => Map'. node_modules/chrome-devtools-frontend/front_end/network_priorities/NetworkPriorities.js(68,48): error TS2339: Property '_symbolicToNumericPriorityMap' does not exist on type '() => Map'. +node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(20,34): error TS2339: Property 'network' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(49,13): error TS2339: Property 'network' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(53,20): error TS2339: Property 'network' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(69,8): error TS2304: Cannot find name 'i'. node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(69,15): error TS2304: Cannot find name 'i'. node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(69,36): error TS2304: Cannot find name 'i'. node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(70,35): error TS2304: Cannot find name 'i'. -node_modules/chrome-devtools-frontend/front_end/network_test_runner/ProductRegistryTestRunner.js(38,22): error TS2345: Argument of type '{ hash: string; prefixes: {}; }[]' is not assignable to parameter of type '{ hash: string; prefixes: { [x: string]: { product: number; type: number; }; }; }[]'. - Type '{ hash: string; prefixes: {}; }' is not assignable to type '{ hash: string; prefixes: { [x: string]: { product: number; type: number; }; }; }'. - Types of property 'prefixes' are incompatible. - Type '{}' is not assignable to type '{ [x: string]: { product: number; type: number; }; }'. - Index signature is missing in type '{}'. +node_modules/chrome-devtools-frontend/front_end/network_test_runner/ProductRegistryTestRunner.js(38,81): error TS2322: Type '{}' is not assignable to type '{ [x: string]: { product: number; type: number; }; }'. + Index signature is missing in type '{}'. node_modules/chrome-devtools-frontend/front_end/object_ui/CustomPreviewComponent.js(31,20): error TS2339: Property 'classList' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/object_ui/CustomPreviewComponent.js(94,30): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/object_ui/CustomPreviewComponent.js(116,11): error TS2339: Property 'consume' does not exist on type 'Event'. @@ -8068,8 +7968,6 @@ node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(196,23): node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(199,15): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(200,23): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(210,7): error TS2322: Type 'Node' is not assignable to type 'Element'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(210,7): error TS2322: Type 'Node' is not assignable to type 'Element'. - Property 'assignedSlot' is missing in type 'Node'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(215,7): error TS2322: Type 'Node' is not assignable to type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(267,21): error TS2339: Property 'DividersData' does not exist on type 'typeof TimelineGrid'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(277,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -8096,12 +7994,23 @@ node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineOverviewPane.js( node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineOverviewPane.js(495,14): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineOverviewPane.js(508,61): error TS2339: Property 'boxInWindow' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(74,36): error TS2554: Expected 0 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(81,20): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(91,33): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(98,5): error TS2554: Expected 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(108,20): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(120,43): error TS2554: Expected 0 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(130,13): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(131,97): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(135,35): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(139,27): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(147,15): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(159,9): error TS2554: Expected 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(189,60): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(220,44): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(254,19): error TS2554: Expected 2 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(321,53): error TS2345: Argument of type 'number' is not assignable to parameter of type 'V'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(347,30): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(355,13): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(67,40): error TS2339: Property 'valuesArray' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(155,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(315,20): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. @@ -8191,8 +8100,6 @@ node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemMa node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemManager.js(345,39): error TS2339: Property 'FilesChangedData' does not exist on type 'typeof IsolatedFileSystemManager'. node_modules/chrome-devtools-frontend/front_end/persistence/NetworkPersistenceManager.js(40,43): error TS2694: Namespace 'Common.EventTarget' has no exported member 'EventDescriptor'. node_modules/chrome-devtools-frontend/front_end/persistence/NetworkPersistenceManager.js(140,55): error TS2339: Property 'hashCode' does not exist on type 'StringConstructor'. -node_modules/chrome-devtools-frontend/front_end/persistence/Persistence.js(62,5): error TS2322: Type '{ dispose: () => void; }' is not assignable to type 'Automapping | DefaultMapping'. - Type '{ dispose: () => void; }' is not assignable to type 'DefaultMapping'. node_modules/chrome-devtools-frontend/front_end/persistence/Persistence.js(62,5): error TS2322: Type '{ dispose: () => void; }' is not assignable to type 'Automapping | DefaultMapping'. Type '{ dispose: () => void; }' is not assignable to type 'DefaultMapping'. Property '_workspace' is missing in type '{ dispose: () => void; }'. @@ -8219,8 +8126,6 @@ node_modules/chrome-devtools-frontend/front_end/persistence/WorkspaceSettingsTab node_modules/chrome-devtools-frontend/front_end/persistence/WorkspaceSettingsTab.js(61,18): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/persistence/WorkspaceSettingsTab.js(112,26): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/persistence/WorkspaceSettingsTab.js(120,39): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/persistence/WorkspaceSettingsTab.js(122,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(30,30): error TS2304: Cannot find name 'Arguments'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(31,5): error TS2300: Duplicate identifier 'ArrayLike'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(46,18): error TS2339: Property 'findAll' does not exist on type 'String'. @@ -8288,6 +8193,11 @@ node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1164,15): node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1169,24): error TS2304: Cannot find name 'KEY'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1169,30): error TS2304: Cannot find name 'VALUE'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1171,15): error TS2339: Property 'inverse' does not exist on type 'Map'. +node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1200,13): error TS2345: Argument of type 'V' is not assignable to parameter of type 'V'. +node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1211,5): error TS2719: Type 'Set' is not assignable to type 'Set'. Two different types with this name exist, but they are unrelated. + Type 'V' is not assignable to type 'V'. Two different types with this name exist, but they are unrelated. +node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1231,20): error TS2345: Argument of type 'V' is not assignable to parameter of type 'V'. +node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1267,22): error TS2339: Property 'keysArray' does not exist on type 'Map>'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1277,14): error TS2339: Property 'pushAll' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1277,40): error TS2339: Property 'valuesArray' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1299,35): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. @@ -8319,25 +8229,427 @@ node_modules/chrome-devtools-frontend/front_end/product_registry/ProductRegistry node_modules/chrome-devtools-frontend/front_end/product_registry/ProductRegistry.js(34,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/product_registry/ProductRegistry.js(55,41): error TS2694: Namespace 'ProductRegistry.Registry' has no exported member 'ProductEntry'. node_modules/chrome-devtools-frontend/front_end/product_registry/ProductRegistry.js(72,26): error TS2339: Property 'ProductEntry' does not exist on type '{ (): void; prototype: { nameForUrl: (parsedUrl: ParsedURL) => string; entryForUrl: (parsedUrl: ParsedURL) => any; typeForUrl: (parsedUrl: ParsedURL) => number; }; }'. -node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1488,1): error TS2345: Argument of type '({ "hash": string; "prefixes": { "": { "product": number; "type": number; }; }; } | { "hash": string; "prefixes": { "*": { "product": number; "type": number; }; }; } | { "hash": string; "prefixes": { "": { "product": number; }; }; } | { "hash": string; "prefixes": { ...; }; } | ... 35 more ... | { ...; })[]' is not assignable to parameter of type '{ hash: string; prefixes: { [x: string]: { product: number; type: number; }; }; }[]'. - Type '{ "hash": string; "prefixes": { "": { "product": number; "type": number; }; }; } | { "hash": string; "prefixes": { "*": { "product": number; "type": number; }; }; } | { "hash": string; "prefixes": { "": { "product": number; }; }; } | { "hash": string; "prefixes": { ...; }; } | ... 35 more ... | { ...; }' is not assignable to type '{ hash: string; prefixes: { [x: string]: { product: number; type: number; }; }; }'. - Type '{ "hash": string; "prefixes": { "": { "product": number; }; }; }' is not assignable to type '{ hash: string; prefixes: { [x: string]: { product: number; type: number; }; }; }'. - Types of property 'prefixes' are incompatible. - Type '{ "": { "product": number; }; }' is not assignable to type '{ [x: string]: { product: number; type: number; }; }'. - Property '""' is incompatible with index signature. - Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. - Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1559,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1563,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1604,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1605,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1606,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1865,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2136,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2136,64): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2136,86): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2208,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2269,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2270,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2322,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2323,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2503,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2856,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2857,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2858,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2859,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2860,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2861,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2862,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2863,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2864,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2865,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3126,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3572,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3573,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3574,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3575,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3576,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3747,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3748,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3770,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3771,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3772,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3773,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3774,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3775,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3776,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3780,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3819,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3826,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3873,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3874,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3957,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3958,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4068,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4069,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4138,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4139,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4203,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4230,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4260,104): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4264,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4265,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4266,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4312,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4480,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4832,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4833,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4834,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4835,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5127,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5137,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5159,70): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5175,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5186,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5202,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5249,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5522,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5523,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5524,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5525,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5539,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5565,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5612,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5613,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5614,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5615,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5616,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5617,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5618,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5619,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5684,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5789,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5820,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5852,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5858,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5859,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5860,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5970,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5971,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5972,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6145,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6151,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6152,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6153,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6154,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6180,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6181,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6182,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6183,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6184,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6185,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6186,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6187,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6193,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6194,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6195,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6196,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6197,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6198,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6199,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6217,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6218,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6225,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6227,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6228,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6229,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6230,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6231,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6232,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6233,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6243,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6270,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6272,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6276,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6294,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6296,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6297,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6298,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6299,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6300,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6303,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6305,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6323,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6324,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6325,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6326,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6327,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6333,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6334,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6335,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6336,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6337,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6338,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6339,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6340,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6341,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6342,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6343,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6344,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6345,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6346,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6347,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6348,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6349,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6350,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6351,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6360,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6361,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6362,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6363,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6364,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6365,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6369,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6382,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6388,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6389,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6404,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6405,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6406,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6425,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6441,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6442,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6445,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6481,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6521,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6560,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6573,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6574,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6575,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6576,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6577,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6578,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6579,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6580,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6581,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6582,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6583,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6615,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6620,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6629,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6637,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6661,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6668,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6675,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6689,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6690,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6699,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6726,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6735,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6737,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6738,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6741,42): error TS2322: Type '{ "product": number; }' is not assignable to type '{ product: number; type: number; }'. + Property 'type' is missing in type '{ "product": number; }'. node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryImpl.js(27,41): error TS2694: Namespace 'ProductRegistry.Registry' has no exported member 'ProductEntry'. node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryImpl.js(103,67): error TS2694: Namespace 'ProductRegistry.Registry' has no exported member 'ProductEntry'. -node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(68,9): error TS2322: Type 'BottomUpProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'BottomUpProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(68,9): error TS2322: Type 'BottomUpProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'BottomUpProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'BottomUpProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(83,15): error TS2339: Property '_remainingNodeInfos' does not exist on type 'ProfileDataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(196,26): error TS2339: Property 'UID' does not exist on type 'ProfileNode'. node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(197,23): error TS2339: Property 'UID' does not exist on type 'ProfileNode'. node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(212,68): error TS2339: Property 'UID' does not exist on type 'ProfileNode'. node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(219,40): error TS2339: Property 'UID' does not exist on type 'ProfileNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(253,19): error TS2339: Property '_takePropertiesFromProfileDataGridNode' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(259,21): error TS2339: Property '_keepOnlyChild' does not exist on type 'ProfileDataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileFlameChart.js(45,49): error TS2551: Property '_colorGenerator' does not exist on type 'typeof ProfileFlameChartDataProvider'. Did you mean 'colorGenerator'? node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileFlameChart.js(52,46): error TS2551: Property '_colorGenerator' does not exist on type 'typeof ProfileFlameChartDataProvider'. Did you mean 'colorGenerator'? node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileFlameChart.js(54,51): error TS2551: Property '_colorGenerator' does not exist on type 'typeof ProfileFlameChartDataProvider'. Did you mean 'colorGenerator'? @@ -8357,7 +8669,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileFlameChart.js node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileFlameChart.js(481,40): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(61,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(63,16): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(73,5): error TS2322: Type 'CPUFlameChartDataProvider' is not assignable to type '{ minimumBoundary(): number; totalTime(): number; formatValue(value: number, precision?: number): string; maxStackDepth(): number; timelineData(): TimelineData; prepareHighlightedEntryInfo(entryIndex: number): Element; ... 6 more ...; textColor(entryIndex: number): string; }'. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(73,5): error TS2322: Type 'CPUFlameChartDataProvider' is not assignable to type '{ minimumBoundary(): number; totalTime(): number; formatValue(value: number, precision?: number): string; maxStackDepth(): number; timelineData(): TimelineData; prepareHighlightedEntryInfo(entryIndex: number): Element; ... 6 more ...; textColor(entryIndex: number): string; }'. Property '_cpuProfile' does not exist on type '{ minimumBoundary(): number; totalTime(): number; formatValue(value: number, precision?: number): string; maxStackDepth(): number; timelineData(): TimelineData; prepareHighlightedEntryInfo(entryIndex: number): Element; ... 6 more ...; textColor(entryIndex: number): string; }'. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(82,43): error TS2555: Expected at least 2 arguments, but got 1. @@ -8370,9 +8681,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(141,2 node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(144,49): error TS2694: Namespace 'SDK.CPUProfilerModel' has no exported member 'EventData'. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(145,43): error TS2694: Namespace 'Protocol' has no exported member 'Profiler'. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(159,26): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(212,65): error TS2345: Argument of type 'CPUProfileType' is not assignable to parameter of type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; } & { showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Type 'CPUProfileType' is not assignable to type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Property 'showProfile' is missing in type 'CPUProfileType'. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(225,25): error TS2694: Namespace 'Protocol' has no exported member 'Profiler'. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(240,24): error TS2694: Namespace 'Protocol' has no exported member 'Profiler'. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(390,21): error TS2339: Property 'secondsToString' does not exist on type 'NumberConstructor'. @@ -8387,7 +8695,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(405,7 node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileView.js(407,24): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(31,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(33,16): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(43,5): error TS2322: Type 'HeapFlameChartDataProvider' is not assignable to type '{ minimumBoundary(): number; totalTime(): number; formatValue(value: number, precision?: number): string; maxStackDepth(): number; timelineData(): TimelineData; prepareHighlightedEntryInfo(entryIndex: number): Element; ... 6 more ...; textColor(entryIndex: number): string; }'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(43,5): error TS2322: Type 'HeapFlameChartDataProvider' is not assignable to type '{ minimumBoundary(): number; totalTime(): number; formatValue(value: number, precision?: number): string; maxStackDepth(): number; timelineData(): TimelineData; prepareHighlightedEntryInfo(entryIndex: number): Element; ... 6 more ...; textColor(entryIndex: number): string; }'. Property '_profile' does not exist on type '{ minimumBoundary(): number; totalTime(): number; formatValue(value: number, precision?: number): string; maxStackDepth(): number; timelineData(): TimelineData; prepareHighlightedEntryInfo(entryIndex: number): Element; ... 6 more ...; textColor(entryIndex: number): string; }'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(52,52): error TS2555: Expected at least 2 arguments, but got 1. @@ -8397,9 +8704,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(82,7 node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(99,12): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(103,12): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(114,26): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(167,65): error TS2345: Argument of type 'SamplingHeapProfileType' is not assignable to parameter of type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; } & { showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Type 'SamplingHeapProfileType' is not assignable to type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Property 'showProfile' is missing in type 'SamplingHeapProfileType'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(181,25): error TS2694: Namespace 'Protocol' has no exported member 'HeapProfiler'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(193,24): error TS2694: Namespace 'Protocol' has no exported member 'HeapProfiler'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(196,60): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -8413,11 +8717,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(389, node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(390,22): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(390,60): error TS2339: Property 'bytesToString' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfileView.js(395,24): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfilerPanel.js(14,9): error TS2345: Argument of type '(HeapSnapshotProfileType | SamplingHeapProfileType)[]' is not assignable to parameter of type '({ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; } & { showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; })[]'. - Type 'HeapSnapshotProfileType | SamplingHeapProfileType' is not assignable to type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; } & { showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Type 'HeapSnapshotProfileType' is not assignable to type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; } & { showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Type 'HeapSnapshotProfileType' is not assignable to type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Property 'showProfile' is missing in type 'HeapSnapshotProfileType'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfilerPanel.js(56,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfilerPanel.js(88,24): error TS2694: Namespace 'Protocol' has no exported member 'HeapProfiler'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapProfilerPanel.js(100,14): error TS2339: Property 'selectLiveObject' does not exist on type 'Widget'. @@ -8435,18 +8734,17 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.j node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(191,27): error TS2339: Property '_sortFields' does not exist on type 'HeapSnapshotSortableDataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(295,41): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(329,72): error TS2339: Property 'offsetHeight' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(394,41): error TS2345: Argument of type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }' is not assignable to parameter of type 'DataGridNode'. - Property '_element' is missing in type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(419,37): error TS2345: Argument of type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }' is not assignable to parameter of type 'DataGridNode'. - Property '_element' is missing in type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(431,76): error TS2339: Property 'peekLast' does not exist on type '({ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; })[]'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(375,36): error TS2339: Property 'filteredOut' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(375,57): error TS2339: Property 'filteredOut' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(387,36): error TS2339: Property 'filteredOut' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(387,57): error TS2339: Property 'filteredOut' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(401,36): error TS2339: Property 'filteredOut' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(401,57): error TS2339: Property 'filteredOut' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(431,76): error TS2339: Property 'peekLast' does not exist on type 'HeapSnapshotGridNode[]'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(433,57): error TS2339: Property 'offsetHeight' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(465,34): error TS2339: Property 'peekLast' does not exist on type '({ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; })[]'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(465,34): error TS2339: Property 'peekLast' does not exist on type 'HeapSnapshotGridNode[]'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(474,19): error TS2551: Property '_allChildren' does not exist on type 'DataGridNode'. Did you mean '_hasChildren'? node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(474,43): error TS2551: Property '_allChildren' does not exist on type 'DataGridNode'. Did you mean '_hasChildren'? -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(492,51): error TS2352: Conversion of type 'DataGridNode' to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Type 'DataGridNode' is not comparable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Property 'dispose' is missing in type 'DataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(522,27): error TS2339: Property 'offsetTop' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(523,40): error TS2339: Property 'offsetHeight' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(554,41): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. @@ -8474,9 +8772,12 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.j node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(673,34): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(675,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(700,24): error TS2694: Namespace 'Protocol' has no exported member 'HeapProfiler'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(776,11): error TS2345: Argument of type 'HeapSnapshotConstructorNode' is not assignable to parameter of type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'HeapSnapshotConstructorNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Property 'nodePosition' is missing in type 'HeapSnapshotConstructorNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(713,67): error TS2339: Property '_name' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(717,30): error TS2339: Property 'populateNodeBySnapshotObjectId' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(776,11): error TS2345: Argument of type 'HeapSnapshotConstructorNode' is not assignable to parameter of type 'HeapSnapshotGridNode'. + Types of property 'createProvider' are incompatible. + Type '() => HeapSnapshotProviderProxy' is not assignable to type '() => { dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. + Type 'HeapSnapshotProviderProxy' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(822,56): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(823,29): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(824,33): error TS2555: Expected at least 2 arguments, but got 1. @@ -8485,45 +8786,31 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.j node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(828,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(834,34): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(835,32): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(887,40): error TS2345: Argument of type 'HeapSnapshotDiffNode' is not assignable to parameter of type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'HeapSnapshotDiffNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Property 'nodePosition' is missing in type 'HeapSnapshotDiffNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(887,40): error TS2345: Argument of type 'HeapSnapshotDiffNode' is not assignable to parameter of type 'HeapSnapshotGridNode'. + Types of property 'createProvider' are incompatible. + Type '() => HeapSnapshotDiffNodesProvider' is not assignable to type '() => { dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. + Type 'HeapSnapshotDiffNodesProvider' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(902,56): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(903,32): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(904,28): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(905,31): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(908,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(914,27): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotDataGrids.js(946,29): error TS2345: Argument of type 'AllocationGridNode' is not assignable to parameter of type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'AllocationGridNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Property 'nodePosition' is missing in type 'AllocationGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(63,16): error TS2352: Conversion of type '{ fieldName1: string; ascending1: string; fieldName2: string; ascending2: string; }' to type 'ComparatorConfig' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Types of property 'ascending1' are incompatible. Type 'string' is not comparable to type 'boolean'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(104,14): error TS2339: Property '_searchMatched' does not exist on type 'HeapSnapshotGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(137,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(156,95): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(163,5): error TS2322: Type '({ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; })[]' is not assignable to type 'DataGridNode[]'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(163,5): error TS2322: Type '({ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; })[]' is not assignable to type 'DataGridNode[]'. - Type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }' is not assignable to type 'DataGridNode'. - Property '_element' is missing in type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(170,39): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'HeapSnapshotGridNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'HeapSnapshotGridNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Type 'this' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Type 'HeapSnapshotGridNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Property 'nodePosition' is missing in type 'HeapSnapshotGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(197,23): error TS2339: Property 'snapshot' does not exist on type 'DataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(222,41): error TS2339: Property 'comparator' does not exist on type 'HeapSnapshotGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(232,48): error TS2339: Property 'comparator' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(265,25): error TS2339: Property '_childHashForEntity' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(271,45): error TS2339: Property '_createChildNode' does not exist on type 'HeapSnapshotGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(322,50): error TS2339: Property 'setEndPosition' does not exist on type 'DataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(365,50): error TS2339: Property 'setStartPosition' does not exist on type 'DataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(393,32): error TS2339: Property '_childHashForNode' does not exist on type 'HeapSnapshotGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(400,47): error TS2339: Property 'comparator' does not exist on type 'HeapSnapshotGridNode'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(403,38): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'HeapSnapshotGridNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'HeapSnapshotGridNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Type 'this' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Type 'HeapSnapshotGridNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Property 'nodePosition' is missing in type 'HeapSnapshotGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(412,15): error TS2339: Property 'sort' does not exist on type 'DataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(433,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(438,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -8545,6 +8832,7 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.j Type 'HeapSnapshotProviderProxy' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. Property '_worker' does not exist on type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(804,15): error TS2577: Return type annotation circularly references itself. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(804,16): error TS2587: JSDoc type 'HeapSnapshotRetainingObjectNode' circularly references itself. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(871,36): error TS2339: Property 'withThousandsSeparator' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(874,34): error TS2339: Property 'withThousandsSeparator' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(892,3): error TS2416: Property 'createProvider' in type 'HeapSnapshotInstanceNode' is not assignable to the same property in base type 'HeapSnapshotGenericObjectNode'. @@ -8561,18 +8849,13 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.j Type '() => HeapSnapshotProviderProxy' is not assignable to type '() => { dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. Type 'HeapSnapshotProviderProxy' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(981,27): error TS2339: Property 'snapshot' does not exist on type 'HeapSnapshotSortableDataGrid'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1000,20): error TS2352: Conversion of type 'DataGridNode' to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Type 'DataGridNode' is not comparable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Property 'dispose' is missing in type 'DataGridNode'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1001,5): error TS2322: Type '(this | ({ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }))[]' is not assignable to type '({ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; })[]'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1001,5): error TS2322: Type '(this | ({ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }))[]' is not assignable to type '({ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; })[]'. - Type 'this | ({ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; })' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'this' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'HeapSnapshotConstructorNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'HeapSnapshotConstructorNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Type 'this' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Type 'HeapSnapshotConstructorNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. - Property 'nodePosition' is missing in type 'HeapSnapshotConstructorNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1001,5): error TS2322: Type '(HeapSnapshotGridNode | this)[]' is not assignable to type 'HeapSnapshotGridNode[]'. + Type 'HeapSnapshotGridNode | this' is not assignable to type 'HeapSnapshotGridNode'. + Type 'this' is not assignable to type 'HeapSnapshotGridNode'. + Type 'HeapSnapshotConstructorNode' is not assignable to type 'HeapSnapshotGridNode'. + Types of property 'createProvider' are incompatible. + Type '() => HeapSnapshotProviderProxy' is not assignable to type '() => { dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. + Type 'HeapSnapshotProviderProxy' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1019,14): error TS2339: Property '_searchMatched' does not exist on type 'HeapSnapshotConstructorNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1029,81): error TS2339: Property 'snapshot' does not exist on type 'HeapSnapshotSortableDataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1140,22): error TS2339: Property 'pushAll' does not exist on type 'any[]'. @@ -8599,12 +8882,8 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.j node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1288,26): error TS2339: Property 'withThousandsSeparator' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1289,22): error TS2339: Property 'withThousandsSeparator' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1306,40): error TS2339: Property 'snapshot' does not exist on type 'HeapSnapshotSortableDataGrid'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1313,39): error TS2345: Argument of type 'AllocationGridNode' is not assignable to parameter of type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'AllocationGridNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1314,7): error TS2322: Type 'AllocationGridNode' is not assignable to type 'this'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1321,39): error TS2339: Property '_createComparator' does not exist on type 'HeapSnapshotSortableDataGrid'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1323,39): error TS2345: Argument of type 'AllocationGridNode' is not assignable to parameter of type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; } & { ...; }'. - Type 'AllocationGridNode' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1347,44): error TS2339: Property 'heapProfilerModel' does not exist on type 'HeapSnapshotSortableDataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(1349,38): error TS2339: Property '_linkifier' does not exist on type 'HeapSnapshotSortableDataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotProxy.js(161,40): error TS2339: Property 'keysArray' does not exist on type 'Map any>'. @@ -8617,11 +8896,11 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotProxy.js(45 node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotProxy.js(457,12): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotProxy.js(507,12): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(42,11): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(48,9): error TS2345: Argument of type 'string' is not assignable to parameter of type 'symbol'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(106,47): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(107,54): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(113,57): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(115,41): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(132,9): error TS2367: This condition will always return 'true' since the types '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; } & { showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }' and 'TrackingHeapSnapshotProfileType' have no overlap. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(192,24): error TS2694: Namespace 'Protocol' has no exported member 'HeapProfiler'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(228,53): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(229,56): error TS2555: Expected at least 2 arguments, but got 1. @@ -8631,16 +8910,9 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(232 node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(233,54): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(238,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(243,80): error TS2339: Property 'bytesToString' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(254,9): error TS2367: This condition will always return 'true' since the types '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; } & { showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }' and 'TrackingHeapSnapshotProfileType' have no overlap. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(256,17): error TS2345: Argument of type 'ToolbarText' is not assignable to parameter of type 'ToolbarComboBox | ToolbarInput'. Type 'ToolbarText' is not assignable to type 'ToolbarInput'. Property '_prompt' is missing in type 'ToolbarText'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(257,5): error TS2322: Type '(ToolbarComboBox | ToolbarInput)[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(257,5): error TS2322: Type '(ToolbarComboBox | ToolbarInput)[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarComboBox | ToolbarInput' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarComboBox' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarComboBox' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarComboBox'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(344,50): error TS2551: Property 'jumpBackwards' does not exist on type 'SearchConfig'. Did you mean 'jumpBackward'? node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(397,25): error TS2339: Property '_loadPromise' does not exist on type 'ProfileHeader'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(405,24): error TS2345: Argument of type 'SearchConfig' is not assignable to parameter of type 'SearchConfig'. @@ -8661,6 +8933,7 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(576 node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(628,37): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(649,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(658,22): error TS2694: Namespace 'Common' has no exported member 'Event'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(667,11): error TS2345: Argument of type 'string' is not assignable to parameter of type 'symbol'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(749,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(793,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(831,11): error TS2555: Expected at least 2 arguments, but got 1. @@ -8669,11 +8942,16 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(875 node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(876,25): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(915,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(946,67): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(947,60): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'HeapSnapshotProfileType' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(heapProfilerModel: HeapProfilerModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'heapProfilerModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'HeapProfilerModel'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(989,12): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1011,12): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1015,12): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1038,26): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1042,5): error TS2322: Type 'ProfileHeader' is not assignable to type 'HeapProfileHeader'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1042,5): error TS2322: Type 'ProfileHeader' is not assignable to type 'HeapProfileHeader'. Property '_heapProfilerModel' is missing in type 'ProfileHeader'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1050,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -8698,15 +8976,17 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(122 node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1248,12): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1252,12): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1258,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1313,11): error TS2345: Argument of type 'HeapSnapshotProfileType' is not assignable to parameter of type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; } & { showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Type 'HeapSnapshotProfileType' is not assignable to type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Property 'showProfile' is missing in type 'HeapSnapshotProfileType'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1358,23): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1430,30): error TS2339: Property 'bytesToString' does not exist on type 'NumberConstructor'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1458,24): error TS2339: Property '_snapshotReceived' does not exist on type 'ProfileType'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1476,61): error TS2339: Property 'toISO8601Compact' does not exist on type 'Date'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1525,23): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1547,44): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1557,77): error TS2339: Property '_profileSamples' does not exist on type 'HeapProfileHeader'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1561,11): error TS2345: Argument of type 'string' is not assignable to parameter of type 'symbol'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1563,11): error TS2345: Argument of type 'string' is not assignable to parameter of type 'symbol'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1578,9): error TS2345: Argument of type 'string' is not assignable to parameter of type 'symbol'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1580,9): error TS2345: Argument of type 'string' is not assignable to parameter of type 'symbol'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1584,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1604,79): error TS2339: Property 'peekLast' does not exist on type 'number[]'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1719,26): error TS2339: Property 'bytesToString' does not exist on type 'NumberConstructor'. @@ -8719,97 +8999,43 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(196 node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1972,33): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(1987,18): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(48,37): error TS2339: Property 'deoptReason' does not exist on type 'ProfileNode'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(97,15): error TS2339: Property 'self' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(97,15): error TS2339: Property 'self' does not exist on type 'ProfileDataGridNode | ProfileDataGridTree'. Property 'self' does not exist on type 'ProfileDataGridTree'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(100,17): error TS2339: Property 'total' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property 'total' does not exist on type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(102,30): error TS2339: Property 'children' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property 'children' does not exist on type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(104,15): error TS2339: Property 'removeChildren' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property 'removeChildren' does not exist on type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(110,19): error TS2339: Property 'appendChild' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property 'appendChild' does not exist on type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(118,37): error TS2339: Property 'childrenByCallUID' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property 'childrenByCallUID' does not exist on type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(123,19): error TS2339: Property 'appendChild' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property 'appendChild' does not exist on type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(131,19): error TS2339: Property '_populated' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property '_populated' does not exist on type 'ProfileDataGridTree'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(133,15): error TS2339: Property '_populated' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property '_populated' does not exist on type 'ProfileDataGridTree'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(135,15): error TS2339: Property 'populateChildren' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property 'populateChildren' does not exist on type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(137,39): error TS2339: Property 'tree' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property 'tree' does not exist on type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(140,17): error TS2339: Property 'sort' does not exist on type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Property 'sort' does not exist on type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(118,27): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((key: any) => any) | ((key: string) => ProfileDataGridNode)' has no compatible call signatures. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(131,19): error TS2339: Property '_populated' does not exist on type 'ProfileDataGridNode | ProfileDataGridTree'. + Property '_populated' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(133,15): error TS2339: Property '_populated' does not exist on type 'ProfileDataGridNode | ProfileDataGridTree'. + Property '_populated' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(140,7): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((comparator: (arg0: T, arg1: T) => any, force: boolean) => any) | ((comparator: (arg0: T, arg1: T) => any, force: boolean) => void)' has no compatible call signatures. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(153,49): error TS2339: Property '_searchMatchedSelfColumn' does not exist on type 'ProfileDataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(158,49): error TS2339: Property '_searchMatchedTotalColumn' does not exist on type 'ProfileDataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(163,49): error TS2339: Property '_searchMatchedFunctionColumn' does not exist on type 'ProfileDataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(170,14): error TS2339: Property 'createTextChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(173,59): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'ProfileDataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(176,20): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(194,20): error TS2339: Property 'createChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(195,83): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'ProfileDataGridNode'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(196,105): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'ProfileDataGridNode'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(206,46): error TS2345: Argument of type 'this[][]' is not assignable to parameter of type '({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; })[][]'. - Type 'this[]' is not assignable to type '({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; })[]'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'ProfileDataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(218,29): error TS2339: Property 'callUID' does not exist on type 'DataGridNode'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(218,42): error TS2352: Conversion of type 'DataGridNode' to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Type 'DataGridNode' is not comparable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'DataGridNode'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(228,40): error TS2352: Conversion of type 'DataGridNode' to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Type 'DataGridNode' is not comparable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'DataGridNode'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(262,43): error TS2345: Argument of type 'this' is not assignable to parameter of type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Type 'ProfileDataGridNode' is not assignable to type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'ProfileDataGridNode'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(312,40): error TS2345: Argument of type 'this' is not assignable to parameter of type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Type 'ProfileDataGridNode' is not assignable to type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'ProfileDataGridNode'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(412,46): error TS2345: Argument of type 'this[][]' is not assignable to parameter of type '({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; })[][]'. - Type 'this[]' is not assignable to type '({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; })[]'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridTree' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridTree' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'this' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'ProfileDataGridTree' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'ProfileDataGridTree'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(412,48): error TS2322: Type 'this' is not assignable to type 'ProfileDataGridNode'. + Type 'ProfileDataGridTree' is not assignable to type 'ProfileDataGridNode'. + Property 'profileNode' is missing in type 'ProfileDataGridTree'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(479,34): error TS2339: Property '_searchMatchedSelfColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(480,34): error TS2339: Property '_searchMatchedTotalColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(481,34): error TS2339: Property '_searchMatchedFunctionColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(486,33): error TS2339: Property '_searchMatchedSelfColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(488,33): error TS2339: Property '_searchMatchedTotalColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(491,33): error TS2339: Property '_searchMatchedSelfColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(493,33): error TS2339: Property '_searchMatchedTotalColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(498,33): error TS2339: Property '_searchMatchedSelfColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(500,33): error TS2339: Property '_searchMatchedTotalColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(505,33): error TS2339: Property '_searchMatchedSelfColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(507,33): error TS2339: Property '_searchMatchedTotalColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(510,33): error TS2339: Property '_searchMatchedSelfColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(512,33): error TS2339: Property '_searchMatchedTotalColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(517,33): error TS2339: Property '_searchMatchedSelfColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(519,33): error TS2339: Property '_searchMatchedTotalColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(525,29): error TS2339: Property '_searchMatchedFunctionColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(527,31): error TS2339: Property '_searchMatchedSelfColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(527,79): error TS2339: Property '_searchMatchedTotalColumn' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(528,31): error TS2339: Property '_searchMatchedFunctionColumn' does not exist on type 'ProfileDataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(640,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(647,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(653,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -8843,12 +9069,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(80,45): node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(84,17): error TS2345: Argument of type '(string | Element)[][]' is not assignable to parameter of type 'ReadonlyArray<[any, any]>'. Type '(string | Element)[]' is not assignable to type '[any, any]'. Property '0' is missing in type '(string | Element)[]'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(127,5): error TS2322: Type '(ToolbarButton | ToolbarComboBox)[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(127,5): error TS2322: Type '(ToolbarButton | ToolbarComboBox)[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarButton | ToolbarComboBox' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarButton'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(136,59): error TS2339: Property 'profile' does not exist on type 'ProfileView'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(136,78): error TS2339: Property 'adjustedTotal' does not exist on type 'ProfileView'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(147,59): error TS2339: Property 'profile' does not exist on type 'ProfileView'. @@ -8871,13 +9091,7 @@ node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(485,23): node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(488,44): error TS2694: Namespace 'Protocol' has no exported member 'Profiler'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(490,25): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(503,24): error TS2694: Namespace 'Protocol' has no exported member 'Profiler'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(72,31): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(74,52): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(76,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(78,31): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(109,15): error TS2339: Property 'key' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(109,45): error TS2339: Property 'altKey' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(111,20): error TS2339: Property 'key' does not exist on type 'Event'. @@ -8915,10 +9129,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(776,26 node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(807,26): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(808,26): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(811,24): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfilesPanel.js(821,26): error TS2345: Argument of type 'CPUProfileType[]' is not assignable to parameter of type '({ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; } & { showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; })[]'. - Type 'CPUProfileType' is not assignable to type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; } & { showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Type 'CPUProfileType' is not assignable to type '{ showProfile(profile: ProfileHeader): Widget; showObject(snapshotObjectId: any, perspectiveName: string): void; }'. - Property 'showProfile' is missing in type 'CPUProfileType'. node_modules/chrome-devtools-frontend/front_end/profiler/TargetsComboBoxController.js(31,38): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/TargetsComboBoxController.js(36,27): error TS2339: Property 'selectedIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/TargetsComboBoxController.js(49,39): error TS2339: Property 'remove' does not exist on type 'Map'. @@ -8929,12 +9139,7 @@ node_modules/chrome-devtools-frontend/front_end/profiler/TargetsComboBoxControll node_modules/chrome-devtools-frontend/front_end/profiler/TargetsComboBoxController.js(97,25): error TS2339: Property 'selectedIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/TopDownProfileDataGrid.js(63,17): error TS2339: Property 'populate' does not exist on type 'TopDownProfileDataGridTree | TopDownProfileDataGridNode'. Property 'populate' does not exist on type 'TopDownProfileDataGridTree'. -node_modules/chrome-devtools-frontend/front_end/profiler/TopDownProfileDataGrid.js(73,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((key: any) => any) | ((key: string) => { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })' has no compatible call signatures. -node_modules/chrome-devtools-frontend/front_end/profiler/TopDownProfileDataGrid.js(76,42): error TS2345: Argument of type 'TopDownProfileDataGridTree | TopDownProfileDataGridNode' is not assignable to parameter of type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Type 'TopDownProfileDataGridNode' is not assignable to type 'ProfileDataGridTree | ({ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { ...; })'. - Type 'TopDownProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; } & { formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Type 'TopDownProfileDataGridNode' is not assignable to type '{ formatValue(value: number, node: any & any): string; formatPercent(value: number, node: any & any): string; linkifyNode(node: any & any): Element; }'. - Property 'formatValue' is missing in type 'TopDownProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/TopDownProfileDataGrid.js(73,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((key: any) => any) | ((key: string) => ProfileDataGridNode)' has no compatible call signatures. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(168,40): error TS2345: Argument of type 'S' is not assignable to parameter of type 'S'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(170,24): error TS2345: Argument of type 'S' is not assignable to parameter of type 'T'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(194,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -8951,7 +9156,6 @@ node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(310 node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(312,16): error TS2339: Property 'sendRequestTime' does not exist on type '(arg0: any) => any'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(422,49): error TS2339: Property 'context' does not exist on type 'Console'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(422,67): error TS2339: Property 'context' does not exist on type 'Console'. -node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(634,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(716,49): error TS2339: Property 'context' does not exist on type 'Console'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(716,67): error TS2339: Property 'context' does not exist on type 'Console'. node_modules/chrome-devtools-frontend/front_end/quick_open/CommandMenu.js(75,10): error TS2339: Property 'runtime' does not exist on type 'Window'. @@ -9008,8 +9212,6 @@ node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(27, node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(28,60): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(32,30): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(32,79): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(34,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(36,64): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(37,57): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(39,57): error TS2555: Expected at least 2 arguments, but got 1. @@ -9019,20 +9221,23 @@ node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(44, node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(48,70): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(52,68): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(53,64): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(55,60): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'AppManifestView' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(resourceTreeModel: ResourceTreeModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'resourceTreeModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'ResourceTreeModel'. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(88,31): error TS2694: Namespace 'Protocol' has no exported member 'Page'. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(116,25): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(139,32): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(158,22): error TS2694: Namespace 'Common' has no exported member 'Event'. +node_modules/chrome-devtools-frontend/front_end/resources/AppManifestView.js(163,14): error TS2339: Property 'pageAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/resources/ApplicationCacheItemsView.js(31,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ApplicationCacheItemsView.js(37,47): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ApplicationCacheItemsView.js(42,28): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/ApplicationCacheItemsView.js(44,22): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/ApplicationCacheItemsView.js(48,44): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ApplicationCacheItemsView.js(59,32): error TS2339: Property 'style' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/resources/ApplicationCacheItemsView.js(67,5): error TS2322: Type 'ToolbarItem[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarItem'. node_modules/chrome-devtools-frontend/front_end/resources/ApplicationCacheItemsView.js(117,22): error TS2339: Property 'type' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/ApplicationCacheItemsView.js(131,30): error TS2339: Property 'type' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/ApplicationCacheItemsView.js(132,44): error TS2555: Expected at least 2 arguments, but got 1. @@ -9171,12 +9376,6 @@ node_modules/chrome-devtools-frontend/front_end/resources/DatabaseQueryView.js(1 node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(31,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(40,47): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(42,53): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(58,5): error TS2322: Type '(ToolbarButton | ToolbarInput)[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. -node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(58,5): error TS2322: Type '(ToolbarButton | ToolbarInput)[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarButton | ToolbarInput' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarButton'. node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(77,18): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(114,37): error TS2339: Property 'valuesArray' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(124,40): error TS2345: Argument of type '{}' is not assignable to parameter of type '{ [x: string]: boolean; }'. @@ -9222,26 +9421,10 @@ node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(191, node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(201,27): error TS2339: Property 'createTextChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(202,45): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(204,27): error TS2339: Property 'createTextChild' does not exist on type 'DocumentFragment'. -node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(211,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(212,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(213,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(215,37): error TS2345: Argument of type 'ToolbarSeparator' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSeparator' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(217,49): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(219,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(221,52): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(224,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(227,37): error TS2345: Argument of type 'ToolbarItem' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(228,27): error TS2339: Property 'placeholder' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(228,41): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(234,37): error TS2345: Argument of type 'ToolbarItem' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(238,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(246,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBViews.js(295,52): error TS2339: Property 'value' does not exist on type 'Element'. @@ -9259,17 +9442,9 @@ node_modules/chrome-devtools-frontend/front_end/resources/ResourcesSection.js(32 node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(11,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(25,46): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(41,49): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(43,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(45,52): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(48,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(50,48): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(52,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(54,55): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(56,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(90,36): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(99,56): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheViews.js(100,27): error TS2555: Expected at least 2 arguments, but got 1. @@ -9289,19 +9464,17 @@ node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkerCacheView node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(12,50): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(31,46): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(42,31): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(48,31): error TS2345: Argument of type 'ToolbarInput' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarInput' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(57,37): error TS2345: Argument of type 'ToolbarCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarCheckbox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(59,36): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(61,32): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(62,37): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(64,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(66,37): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(67,37): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(69,75): error TS2694: Namespace 'Common.EventTarget' has no exported member 'EventDescriptor'. +node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(71,63): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'ServiceWorkersView' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(serviceWorkerManager: ServiceWorkerManager) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'serviceWorkerManager' and 'model' are incompatible. + Type 'T' is not assignable to type 'ServiceWorkerManager'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(120,7): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(121,7): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(150,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -9311,12 +9484,8 @@ node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js( node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(293,56): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(298,47): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(298,85): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(300,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(302,30): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(302,87): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(304,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(307,68): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(308,68): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/ServiceWorkersView.js(309,69): error TS2555: Expected at least 2 arguments, but got 1. @@ -9367,9 +9536,6 @@ node_modules/chrome-devtools-frontend/front_end/resources/StorageItemsView.js(15 node_modules/chrome-devtools-frontend/front_end/resources/StorageItemsView.js(17,25): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/StorageItemsView.js(18,43): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/StorageItemsView.js(22,44): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/resources/StorageItemsView.js(27,43): error TS2345: Argument of type 'ToolbarButton | ToolbarInput' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/resources/StorageItemsView.js(40,60): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(arg0: any) => any'. Type 'Function' provides no match for the signature '(arg0: any): any'. node_modules/chrome-devtools-frontend/front_end/resources/StorageItemsView.js(49,45): error TS2555: Expected at least 2 arguments, but got 1. @@ -9393,10 +9559,13 @@ node_modules/chrome-devtools-frontend/front_end/screencast/InputModel.js(112,44) node_modules/chrome-devtools-frontend/front_end/screencast/InputModel.js(112,70): error TS2339: Property 'metaKey' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/screencast/InputModel.js(112,96): error TS2339: Property 'shiftKey' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/screencast/ScreencastApp.js(12,47): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/screencast/ScreencastApp.js(16,61): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'ScreencastApp' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(screenCaptureModel: ScreenCaptureModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'screenCaptureModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'ScreenCaptureModel'. node_modules/chrome-devtools-frontend/front_end/screencast/ScreencastApp.js(85,35): error TS2345: Argument of type 'ScreencastView' is not assignable to parameter of type 'boolean'. -node_modules/chrome-devtools-frontend/front_end/screencast/ScreencastApp.js(107,5): error TS2322: Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarToggle'. node_modules/chrome-devtools-frontend/front_end/screencast/ScreencastApp.js(121,5): error TS2322: Type 'ScreencastApp' is not assignable to type '{ presentUI(document: Document): void; }'. Property '_enabledSetting' does not exist on type '{ presentUI(document: Document): void; }'. node_modules/chrome-devtools-frontend/front_end/screencast/ScreencastView.js(56,42): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -9452,7 +9621,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/CPUProfileDataModel.js(117,3 node_modules/chrome-devtools-frontend/front_end/sdk/CPUProfileDataModel.js(132,39): error TS2694: Namespace 'Protocol' has no exported member 'Profiler'. node_modules/chrome-devtools-frontend/front_end/sdk/CPUProfileDataModel.js(289,40): error TS2339: Property 'depth' does not exist on type 'CPUProfileNode'. node_modules/chrome-devtools-frontend/front_end/sdk/CPUProfileDataModel.js(289,51): error TS2345: Argument of type 'ProfileNode' is not assignable to parameter of type 'CPUProfileNode'. - Property 'positionTicks' is missing in type 'ProfileNode'. node_modules/chrome-devtools-frontend/front_end/sdk/CPUProfileDataModel.js(300,41): error TS2339: Property 'depth' does not exist on type 'CPUProfileNode'. node_modules/chrome-devtools-frontend/front_end/sdk/CPUProfileDataModel.js(300,52): error TS2345: Argument of type 'ProfileNode' is not assignable to parameter of type 'CPUProfileNode'. node_modules/chrome-devtools-frontend/front_end/sdk/CPUProfileDataModel.js(307,19): error TS2339: Property 'depth' does not exist on type 'CPUProfileNode'. @@ -9556,7 +9724,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/CSSProperty.js(18,24): error node_modules/chrome-devtools-frontend/front_end/sdk/CSSProperty.js(39,24): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSProperty.js(168,56): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSProperty.js(170,17): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/sdk/CSSProperty.js(259,32): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSRule.js(9,24): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSRule.js(33,32): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSRule.js(33,98): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. @@ -9574,7 +9741,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/CSSStyleDeclaration.js(8,24) node_modules/chrome-devtools-frontend/front_end/sdk/CSSStyleDeclaration.js(41,47): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSStyleDeclaration.js(50,24): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSStyleSheetHeader.js(11,24): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. -node_modules/chrome-devtools-frontend/front_end/sdk/CSSStyleSheetHeader.js(40,5): error TS2322: Type 'StaticContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSStyleSheetHeader.js(40,5): error TS2322: Type 'StaticContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. Property '_contentURL' does not exist on type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/sdk/Connections.js(10,52): error TS2694: Namespace 'Protocol.InspectorBackend.Connection' has no exported member 'Params'. @@ -9628,20 +9794,19 @@ node_modules/chrome-devtools-frontend/front_end/sdk/DOMDebuggerModel.js(659,9): node_modules/chrome-devtools-frontend/front_end/sdk/DOMDebuggerModel.js(661,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sdk/DOMDebuggerModel.js(663,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sdk/DOMDebuggerModel.js(665,9): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/sdk/DOMDebuggerModel.js(673,59): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'DOMDebuggerManager' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(domDebuggerModel: DOMDebuggerModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'domDebuggerModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'DOMDebuggerModel'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(47,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(59,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(136,53): error TS2339: Property 'documentElement' does not exist on type 'DOMDocument'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(137,28): error TS2339: Property 'documentElement' does not exist on type 'DOMDocument'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(138,53): error TS2339: Property 'body' does not exist on type 'DOMDocument'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(139,28): error TS2339: Property 'body' does not exist on type 'DOMDocument'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(369,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(396,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(419,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(433,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(447,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(454,35): error TS2694: Namespace 'SDK.DOMNode' has no exported member 'Attribute'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(507,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(519,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(554,31): error TS2339: Property 'index' does not exist on type 'DOMNode'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(555,16): error TS2339: Property 'index' does not exist on type 'DOMNode'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(590,25): error TS2694: Namespace 'Protocol' has no exported member 'Page'. @@ -9650,9 +9815,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(659,32): error T node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(672,32): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(687,32): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(743,24): error TS2339: Property 'remove' does not exist on type 'any[]'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(751,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(751,50): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(768,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(852,31): error TS2339: Property 'baseURL' does not exist on type 'DOMNode'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(853,65): error TS2339: Property 'baseURL' does not exist on type 'DOMNode'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(860,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -9665,14 +9828,9 @@ node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(970,13): error T node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1042,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1062,26): error TS2339: Property 'domAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1070,12): error TS2339: Property 'registerDOMDispatcher' does not exist on type 'Target'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1096,16): error TS2352: Conversion of type 'OverlayModel' to type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; } & { ...; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Type 'OverlayModel' is not comparable to type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }'. - Property '_domModel' does not exist on type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1165,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1176,34): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1188,46): error TS2339: Property 'valuesArray' does not exist on type 'Set'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1203,34): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1208,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1214,16): error TS2345: Argument of type 'T' is not assignable to parameter of type 'T'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1220,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1235,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. @@ -9735,17 +9893,15 @@ node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(250,43): er node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(281,43): error TS2694: Namespace 'SDK.DebuggerModel' has no exported member 'SetBreakpointResult'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(304,43): error TS2694: Namespace 'SDK.DebuggerModel' has no exported member 'SetBreakpointResult'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(319,24): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. +node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(332,32): error TS2587: JSDoc type 'BreakLocation' circularly references itself. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(346,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(347,34): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(355,24): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(356,24): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(389,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(419,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(421,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(429,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(431,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(431,50): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(432,24): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(433,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(434,32): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(435,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -9812,12 +9968,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/EmulationModel.js(11,35): er node_modules/chrome-devtools-frontend/front_end/sdk/EmulationModel.js(12,30): error TS2339: Property 'pageAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/EmulationModel.js(13,43): error TS2339: Property 'deviceOrientationAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/EmulationModel.js(51,24): error TS2694: Namespace 'Protocol' has no exported member 'PageAgent'. -node_modules/chrome-devtools-frontend/front_end/sdk/EmulationModel.js(65,5): error TS2322: Type 'OverlayModel' is not assignable to type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; } & { ...; }'. - Type 'OverlayModel' is not assignable to type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }'. -node_modules/chrome-devtools-frontend/front_end/sdk/EmulationModel.js(65,5): error TS2322: Type 'OverlayModel' is not assignable to type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; } & { ...; }'. - Type 'OverlayModel' is not assignable to type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }'. - Property '_domModel' does not exist on type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }'. -node_modules/chrome-devtools-frontend/front_end/sdk/EmulationModel.js(148,5): error TS2322: Type '{ enabled: boolean; configuration: string; }' is not assignable to type '{ enabled: boolean; configuration: string; scriptId: string; }'. node_modules/chrome-devtools-frontend/front_end/sdk/EmulationModel.js(148,5): error TS2322: Type '{ enabled: boolean; configuration: string; }' is not assignable to type '{ enabled: boolean; configuration: string; scriptId: string; }'. Property 'scriptId' is missing in type '{ enabled: boolean; configuration: string; }'. node_modules/chrome-devtools-frontend/front_end/sdk/FilmStripModel.js(77,30): error TS2339: Property 'upperBound' does not exist on type 'Frame[]'. @@ -9830,6 +9980,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(23,15): err node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(28,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(33,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(38,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. +node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(45,12): error TS2502: 'child' is referenced directly or indirectly in its own type annotation. node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(48,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(53,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(58,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -9867,7 +10018,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(122,25): e node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(128,36): error TS2551: Property '_connectionTypes' does not exist on type 'typeof NetworkManager'. Did you mean '_connectionType'? node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(130,26): error TS2551: Property '_connectionTypes' does not exist on type 'typeof NetworkManager'. Did you mean '_connectionType'? node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(131,34): error TS2551: Property '_connectionTypes' does not exist on type 'typeof NetworkManager'. Did you mean '_connectionType'? -node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(154,5): error TS2322: Type '{}' is not assignable to type '{ [x: string]: string; }'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(154,5): error TS2322: Type '{}' is not assignable to type '{ [x: string]: string; }'. Index signature is missing in type '{}'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(166,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -9972,6 +10122,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1025,37): node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1027,39): error TS2339: Property 'set' does not exist on type 'Multimap'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1050,82): error TS2339: Property 'valuesArray' does not exist on type 'Multimap'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1059,68): error TS2339: Property 'keysArray' does not exist on type 'Multimap'. +node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1084,19): error TS2339: Property 'networkAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1101,35): error TS2345: Argument of type '{}' is not assignable to parameter of type '{ [x: string]: string; }'. Index signature is missing in type '{}'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1115,24): error TS2694: Namespace 'Protocol' has no exported member 'NetworkAgent'. @@ -10049,15 +10200,11 @@ node_modules/chrome-devtools-frontend/front_end/sdk/NetworkRequest.js(1131,20): node_modules/chrome-devtools-frontend/front_end/sdk/NetworkRequest.js(1134,20): error TS2339: Property 'ContentData' does not exist on type 'typeof NetworkRequest'. node_modules/chrome-devtools-frontend/front_end/sdk/OverlayModel.js(16,12): error TS2339: Property 'registerOverlayDispatcher' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/OverlayModel.js(17,33): error TS2339: Property 'overlayAgent' does not exist on type 'Target'. -node_modules/chrome-devtools-frontend/front_end/sdk/OverlayModel.js(35,72): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; } & { ...; }'. - Type 'OverlayModel' is not assignable to type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; } & { ...; }'. - Type 'OverlayModel' is not assignable to type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }'. - Type 'this' is not assignable to type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }'. - Type 'OverlayModel' is not assignable to type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }'. - Property '_domModel' does not exist on type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }'. node_modules/chrome-devtools-frontend/front_end/sdk/OverlayModel.js(81,22): error TS2339: Property '_highlightDisabled' does not exist on type 'typeof OverlayModel'. node_modules/chrome-devtools-frontend/front_end/sdk/OverlayModel.js(85,22): error TS2339: Property '_highlightDisabled' does not exist on type 'typeof OverlayModel'. node_modules/chrome-devtools-frontend/front_end/sdk/OverlayModel.js(110,9): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/sdk/OverlayModel.js(119,5): error TS2322: Type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }' is not assignable to type 'DefaultHighlighter'. + Property '_model' is missing in type '{ highlightDOMNode(node: DOMNode, config: any, backendNodeId?: any, objectId?: any): void; setInspectMode(mode: any, config: any): Promise; highlightFrame(frameId: any): void; }'. node_modules/chrome-devtools-frontend/front_end/sdk/OverlayModel.js(123,24): error TS2694: Namespace 'Protocol' has no exported member 'Overlay'. node_modules/chrome-devtools-frontend/front_end/sdk/OverlayModel.js(141,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/OverlayModel.js(143,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. @@ -10100,7 +10247,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/ProfileTreeModel.js(12,26): node_modules/chrome-devtools-frontend/front_end/sdk/ProfileTreeModel.js(80,10): error TS2339: Property 'depth' does not exist on type 'ProfileNode'. node_modules/chrome-devtools-frontend/front_end/sdk/ProfileTreeModel.js(86,26): error TS2339: Property 'depth' does not exist on type 'ProfileNode'. node_modules/chrome-devtools-frontend/front_end/sdk/ProfileTreeModel.js(93,15): error TS2339: Property 'depth' does not exist on type 'ProfileNode'. -node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(45,5): error TS2322: Type 'LocalJSONObject' is not assignable to type 'RemoteObject'. node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(45,5): error TS2322: Type 'LocalJSONObject' is not assignable to type 'RemoteObject'. Types of property 'callFunctionJSON' are incompatible. Type '(functionDeclaration: (this: any) => any, args: any[], callback: (arg0: any) => any) => void' is not assignable to type '(functionDeclaration: (this: any, ...arg1: any[]) => T, args: any[], callback: (arg0: T) => any) => void'. @@ -10165,7 +10311,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1179,3): err Types of parameters 'functionDeclaration' and 'functionDeclaration' are incompatible. node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1234,21): error TS2694: Namespace 'SDK' has no exported member 'CallFunctionResult'. node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1265,21): error TS2694: Namespace 'SDK' has no exported member 'CallFunctionResult'. -node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1325,5): error TS2322: Type 'Promise<{ properties: RemoteObjectProperty[]; internalProperties: RemoteObjectProperty[]; }>' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1325,5): error TS2322: Type 'Promise<{ properties: RemoteObjectProperty[]; internalProperties: RemoteObjectProperty[]; }>' is not assignable to type 'Promise'. Type '{ properties: RemoteObjectProperty[]; internalProperties: RemoteObjectProperty[]; }' is not assignable to type 'RemoteObject'. Property 'customPreview' is missing in type '{ properties: RemoteObjectProperty[]; internalProperties: RemoteObjectProperty[]; }'. @@ -10184,6 +10329,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/Resource.js(241,13): error T node_modules/chrome-devtools-frontend/front_end/sdk/Resource.js(263,61): error TS2339: Property 'pageAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/ResourceTreeModel.js(44,26): error TS2339: Property 'pageAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/ResourceTreeModel.js(48,12): error TS2339: Property 'registerPageDispatcher' does not exist on type 'Target'. +node_modules/chrome-devtools-frontend/front_end/sdk/ResourceTreeModel.js(80,56): error TS2339: Property 'valuesArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/sdk/ResourceTreeModel.js(117,24): error TS2694: Namespace 'Protocol' has no exported member 'Page'. node_modules/chrome-devtools-frontend/front_end/sdk/ResourceTreeModel.js(161,24): error TS2694: Namespace 'Protocol' has no exported member 'Page'. node_modules/chrome-devtools-frontend/front_end/sdk/ResourceTreeModel.js(162,24): error TS2694: Namespace 'Protocol' has no exported member 'Page'. @@ -10227,13 +10373,11 @@ node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(96,39): erro node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(125,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(133,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(168,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(173,5): error TS2322: Type 'RemoteObjectImpl' is not assignable to type 'RemoteObject'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(173,5): error TS2322: Type 'RemoteObjectImpl' is not assignable to type 'RemoteObject'. Types of property 'callFunctionJSON' are incompatible. Type '(functionDeclaration: (this: any) => any, args: any[], callback: (arg0: any) => any) => void' is not assignable to type '(functionDeclaration: (this: any, ...arg1: any[]) => T, args: any[], callback: (arg0: T) => any) => void'. Types of parameters 'functionDeclaration' and 'functionDeclaration' are incompatible. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(179,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(184,5): error TS2322: Type 'ScopeRemoteObject' is not assignable to type 'RemoteObject'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(184,5): error TS2322: Type 'ScopeRemoteObject' is not assignable to type 'RemoteObject'. Types of property 'callFunctionJSON' are incompatible. Type '(functionDeclaration: (this: any) => any, args: any[], callback: (arg0: any) => any) => void' is not assignable to type '(functionDeclaration: (this: any, ...arg1: any[]) => T, args: any[], callback: (arg0: T) => any) => void'. @@ -10259,9 +10403,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(489,36): err node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(492,18): error TS2339: Property 'CompileScriptResult' does not exist on type 'typeof RuntimeModel'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(503,18): error TS2339: Property 'EvaluationOptions' does not exist on type 'typeof RuntimeModel'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(507,36): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(508,25): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(511,18): error TS2339: Property 'EvaluationResult' does not exist on type 'typeof RuntimeModel'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(515,25): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(518,18): error TS2339: Property 'QueryObjectResult' does not exist on type 'typeof RuntimeModel'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(523,30): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(526,30): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -10296,15 +10438,14 @@ node_modules/chrome-devtools-frontend/front_end/sdk/ScreenCaptureModel.js(152,24 node_modules/chrome-devtools-frontend/front_end/sdk/ScreenCaptureModel.js(160,24): error TS2694: Namespace 'Protocol' has no exported member 'Page'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(39,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(143,52): error TS2339: Property 'debuggerAgent' does not exist on type 'Target'. -node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(159,5): error TS2322: Type 'StaticContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(159,5): error TS2322: Type 'StaticContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. Property '_contentURL' does not exist on type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(174,43): error TS2339: Property 'debuggerAgent' does not exist on type 'Target'. -node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(190,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(190,50): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(190,95): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(190,127): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(190,158): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. +node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(198,16): error TS2345: Argument of type '"Script failed to parse"' is not assignable to parameter of type 'symbol'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(203,54): error TS2339: Property 'debuggerAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(247,31): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(251,54): error TS2339: Property 'debuggerAgent' does not exist on type 'Target'. @@ -10313,7 +10454,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/ServerTiming.js(20,41): erro node_modules/chrome-devtools-frontend/front_end/sdk/ServerTiming.js(110,26): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sdk/ServerTiming.js(129,32): error TS2345: Argument of type 'TemplateStringsArray' is not assignable to parameter of type 'string | string[]'. Type 'TemplateStringsArray' is not assignable to type 'string[]'. - Property 'pop' is missing in type 'TemplateStringsArray'. node_modules/chrome-devtools-frontend/front_end/sdk/ServerTiming.js(134,32): error TS2345: Argument of type 'TemplateStringsArray' is not assignable to parameter of type 'string | string[]'. Type 'TemplateStringsArray' is not assignable to type 'string[]'. node_modules/chrome-devtools-frontend/front_end/sdk/ServerTiming.js(139,30): error TS2345: Argument of type 'TemplateStringsArray' is not assignable to parameter of type 'string | string[]'. @@ -10361,10 +10501,8 @@ node_modules/chrome-devtools-frontend/front_end/sdk/SourceMap.js(196,28): error node_modules/chrome-devtools-frontend/front_end/sdk/SourceMap.js(198,25): error TS2339: Property '_base64Map' does not exist on type 'typeof TextSourceMap'. node_modules/chrome-devtools-frontend/front_end/sdk/SourceMap.js(200,27): error TS2339: Property '_base64Map' does not exist on type 'typeof TextSourceMap'. node_modules/chrome-devtools-frontend/front_end/sdk/SourceMap.js(272,30): error TS2339: Property 'keysArray' does not exist on type 'Map'. -node_modules/chrome-devtools-frontend/front_end/sdk/SourceMap.js(284,7): error TS2322: Type 'StaticContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/sdk/SourceMap.js(284,7): error TS2322: Type 'StaticContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. Property '_contentURL' does not exist on type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. -node_modules/chrome-devtools-frontend/front_end/sdk/SourceMap.js(285,5): error TS2322: Type 'CompilerSourceMappingContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/sdk/SourceMap.js(285,5): error TS2322: Type 'CompilerSourceMappingContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. Property '_sourceURL' does not exist on type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/sdk/SourceMap.js(325,26): error TS2339: Property 'upperBound' does not exist on type 'SourceMapEntry[]'. @@ -10402,6 +10540,8 @@ node_modules/chrome-devtools-frontend/front_end/sdk/Target.js(16,52): error TS26 node_modules/chrome-devtools-frontend/front_end/sdk/Target.js(148,48): error TS2339: Property 'valuesArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/sdk/Target.js(159,53): error TS2345: Argument of type 'new (arg1: Target) => T' is not assignable to parameter of type 'new (arg1: Target) => SDKModel'. Type 'T' is not assignable to type 'SDKModel'. +node_modules/chrome-devtools-frontend/front_end/sdk/Target.js(166,48): error TS2345: Argument of type 'new (arg1: Target) => T' is not assignable to parameter of type 'new (arg1: Target) => SDKModel'. + Type 'T' is not assignable to type 'SDKModel'. node_modules/chrome-devtools-frontend/front_end/sdk/Target.js(191,34): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(15,120): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(104,35): error TS2345: Argument of type 'new (arg1: Target) => T' is not assignable to parameter of type 'new (arg1: Target) => SDKModel'. @@ -10423,34 +10563,17 @@ node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(169,31): er node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(177,42): error TS2345: Argument of type 'Function' is not assignable to parameter of type 'new (arg1: Target) => any'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(209,21): error TS2339: Property 'remove' does not exist on type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; }[]'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(216,52): error TS2694: Namespace 'Protocol.InspectorBackend.Connection' has no exported member 'Factory'. -node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(221,33): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; } & { targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'TargetManager' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; } & { targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'TargetManager' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'this' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'TargetManager' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Property 'targetAdded' is missing in type 'TargetManager'. -node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(224,72): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; } & { targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'TargetManager' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; } & { targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'TargetManager' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'this' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'TargetManager' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Property 'targetAdded' is missing in type 'TargetManager'. +node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(237,34): error TS2345: Argument of type 'Function' is not assignable to parameter of type 'new (arg1: Target) => any'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(267,19): error TS2339: Property 'remove' does not exist on type 'Target[]'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(279,34): error TS2345: Argument of type 'Function' is not assignable to parameter of type 'new (arg1: Target) => any'. -node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(329,11): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; } & { targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'this' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(329,25): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(332,72): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; } & { targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'this' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(351,35): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(352,12): error TS2339: Property 'runtimeAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(356,52): error TS2694: Namespace 'Protocol.InspectorBackend.Connection' has no exported member 'Params'. -node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(364,7): error TS2322: Type 'WebSocketConnection' is not assignable to type '{ sendMessage(message: string): void; disconnect(): Promise; }'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(364,7): error TS2322: Type 'WebSocketConnection' is not assignable to type '{ sendMessage(message: string): void; disconnect(): Promise; }'. Property '_socket' does not exist on type '{ sendMessage(message: string): void; disconnect(): Promise; }'. -node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(366,7): error TS2322: Type 'StubConnection' is not assignable to type '{ sendMessage(message: string): void; disconnect(): Promise; }'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(366,7): error TS2322: Type 'StubConnection' is not assignable to type '{ sendMessage(message: string): void; disconnect(): Promise; }'. Property '_onMessage' does not exist on type '{ sendMessage(message: string): void; disconnect(): Promise; }'. -node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(368,7): error TS2322: Type 'MainConnection' is not assignable to type '{ sendMessage(message: string): void; disconnect(): Promise; }'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(368,7): error TS2322: Type 'MainConnection' is not assignable to type '{ sendMessage(message: string): void; disconnect(): Promise; }'. Property '_onMessage' does not exist on type '{ sendMessage(message: string): void; disconnect(): Promise; }'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(401,38): error TS2339: Property 'targetAgent' does not exist on type 'Target'. @@ -10460,16 +10583,13 @@ node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(427,34): er node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(483,24): error TS2694: Namespace 'Protocol' has no exported member 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(501,24): error TS2694: Namespace 'Protocol' has no exported member 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(530,24): error TS2694: Namespace 'Protocol' has no exported member 'Target'. +node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(552,12): error TS2339: Property 'runtimeAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(581,24): error TS2694: Namespace 'Protocol' has no exported member 'TargetAgent'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(583,52): error TS2694: Namespace 'Protocol.InspectorBackend.Connection' has no exported member 'Params'. -node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(589,5): error TS2322: Type 'ChildConnection' is not assignable to type '{ sendMessage(message: string): void; disconnect(): Promise; }'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(589,5): error TS2322: Type 'ChildConnection' is not assignable to type '{ sendMessage(message: string): void; disconnect(): Promise; }'. Property '_agent' does not exist on type '{ sendMessage(message: string): void; disconnect(): Promise; }'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(598,24): error TS2694: Namespace 'Protocol' has no exported member 'TargetAgent'. node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(600,52): error TS2694: Namespace 'Protocol.InspectorBackend.Connection' has no exported member 'Params'. -node_modules/chrome-devtools-frontend/front_end/sdk/TargetManager.js(672,1): error TS2322: Type 'TargetManager' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; } & { targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Type 'TargetManager' is not assignable to type '{ targetAdded(target: Target): void; targetRemoved(target: Target): void; }'. - Property 'targetAdded' is missing in type 'TargetManager'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingManager.js(13,42): error TS2694: Namespace 'SDK.TracingManager' has no exported member 'EventPayload'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingManager.js(36,33): error TS2339: Property 'tracingAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingManager.js(37,12): error TS2339: Property 'registerTracingDispatcher' does not exist on type 'Target'. @@ -10481,7 +10601,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(133,42): err node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(179,34): error TS2694: Namespace 'SDK.TracingManager' has no exported member 'EventPayload'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(250,47): error TS2339: Property 'id' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(254,37): error TS2339: Property 'id' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(283,5): error TS2322: Type 'NamedObject[]' is not assignable to type 'Process[]'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(283,5): error TS2322: Type 'NamedObject[]' is not assignable to type 'Process[]'. Type 'NamedObject' is not assignable to type 'Process'. Property '_threads' is missing in type 'NamedObject'. @@ -10499,8 +10618,8 @@ node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(576,43): err node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(576,55): error TS2339: Property 'ordinal' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(647,34): error TS2694: Namespace 'SDK.TracingManager' has no exported member 'EventPayload'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(649,15): error TS2577: Return type annotation circularly references itself. +node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(649,16): error TS2587: JSDoc type 'ObjectSnapshot' circularly references itself. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(859,34): error TS2694: Namespace 'SDK.TracingManager' has no exported member 'EventPayload'. -node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(870,5): error TS2322: Type 'NamedObject[]' is not assignable to type 'Thread[]'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(870,5): error TS2322: Type 'NamedObject[]' is not assignable to type 'Thread[]'. Type 'NamedObject' is not assignable to type 'Thread'. Property '_process' is missing in type 'NamedObject'. @@ -10509,6 +10628,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(888,23): err node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(889,18): error TS2339: Property 'stableSort' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(917,18): error TS2339: Property 'remove' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(921,34): error TS2694: Namespace 'SDK.TracingManager' has no exported member 'EventPayload'. +node_modules/chrome-devtools-frontend/front_end/sdk_test_runner/PageMockTestRunner.js(17,20): error TS2554: Expected 5 arguments, but got 4. node_modules/chrome-devtools-frontend/front_end/sdk_test_runner/PageMockTestRunner.js(88,20): error TS2339: Property 'hashCode' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/security/SecurityModel.js(14,34): error TS2339: Property 'securityAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/security/SecurityModel.js(15,12): error TS2339: Property 'registerSecurityDispatcher' does not exist on type 'Target'. @@ -10527,6 +10647,12 @@ node_modules/chrome-devtools-frontend/front_end/security/SecurityPanel.js(15,25) node_modules/chrome-devtools-frontend/front_end/security/SecurityPanel.js(21,31): error TS2694: Namespace 'Protocol' has no exported member 'Network'. node_modules/chrome-devtools-frontend/front_end/security/SecurityPanel.js(24,45): error TS2694: Namespace 'Security.SecurityPanel' has no exported member 'Origin'. node_modules/chrome-devtools-frontend/front_end/security/SecurityPanel.js(24,77): error TS2694: Namespace 'Security.SecurityPanel' has no exported member 'OriginState'. +node_modules/chrome-devtools-frontend/front_end/security/SecurityPanel.js(30,61): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'SecurityPanel' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(securityModel: SecurityModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'securityModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'SecurityModel'. node_modules/chrome-devtools-frontend/front_end/security/SecurityPanel.js(37,57): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/security/SecurityPanel.js(47,9): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/security/SecurityPanel.js(60,9): error TS2339: Property 'consume' does not exist on type 'Event'. @@ -10672,11 +10798,9 @@ node_modules/chrome-devtools-frontend/front_end/settings/FrameworkBlackboxSettin node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(39,25): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(45,10): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(46,24): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(51,48): error TS2345: Argument of type 'ToolbarItem' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarItem' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(54,43): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(69,55): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(85,5): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. +node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(85,5): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ...; }, insertBefore?: { ...'. Property 'appendApplicableItems' is missing in type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }'. node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(100,15): error TS2339: Property 'keyCode' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(119,31): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -10697,8 +10821,13 @@ node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(289,5 node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(311,10): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(312,10): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/settings/SettingsScreen.js(313,10): error TS2339: Property 'runtime' does not exist on type 'Window'. +node_modules/chrome-devtools-frontend/front_end/snippets/ScriptSnippetModel.js(53,56): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'ScriptSnippetModel' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(debuggerModel: DebuggerModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'debuggerModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'DebuggerModel'. node_modules/chrome-devtools-frontend/front_end/snippets/ScriptSnippetModel.js(70,35): error TS2339: Property 'remove' does not exist on type 'Map'. -node_modules/chrome-devtools-frontend/front_end/snippets/ScriptSnippetModel.js(113,5): error TS2322: Type 'SnippetsProject' is not assignable to type '{ workspace(): Workspace; id(): string; type(): string; isServiceProject(): boolean; displayName(): string; requestMetadata(uiSourceCode: UISourceCode): Promise; ... 17 more ...; uiSourceCodes(): UISourceCode[]; }'. node_modules/chrome-devtools-frontend/front_end/snippets/ScriptSnippetModel.js(113,5): error TS2322: Type 'SnippetsProject' is not assignable to type '{ workspace(): Workspace; id(): string; type(): string; isServiceProject(): boolean; displayName(): string; requestMetadata(uiSourceCode: UISourceCode): Promise; ... 17 more ...; uiSourceCodes(): UISourceCode[]; }'. Property '_model' does not exist on type '{ workspace(): Workspace; id(): string; type(): string; isServiceProject(): boolean; displayName(): string; requestMetadata(uiSourceCode: UISourceCode): Promise; ... 17 more ...; uiSourceCodes(): UISourceCode[]; }'. node_modules/chrome-devtools-frontend/front_end/snippets/ScriptSnippetModel.js(146,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -10714,11 +10843,6 @@ node_modules/chrome-devtools-frontend/front_end/snippets/ScriptSnippetModel.js(3 node_modules/chrome-devtools-frontend/front_end/snippets/SnippetStorage.js(62,27): error TS2339: Property 'valuesArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/snippets/SnippetsQuickOpen.js(30,12): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/source_frame/FontView.js(38,11): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/source_frame/FontView.js(52,5): error TS2322: Type 'ToolbarText[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. -node_modules/chrome-devtools-frontend/front_end/source_frame/FontView.js(52,5): error TS2322: Type 'ToolbarText[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarText' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarText' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarText'. node_modules/chrome-devtools-frontend/front_end/source_frame/FontView.js(62,16): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/source_frame/FontView.js(78,21): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/source_frame/FontView.js(79,19): error TS2339: Property 'createTextChild' does not exist on type 'Element'. @@ -10741,12 +10865,6 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/FontView.js(152,29) node_modules/chrome-devtools-frontend/front_end/source_frame/ImageView.js(38,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/source_frame/ImageView.js(52,81): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/source_frame/ImageView.js(58,36): error TS2339: Property 'createChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/source_frame/ImageView.js(68,5): error TS2322: Type '(ToolbarSeparator | ToolbarText)[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. -node_modules/chrome-devtools-frontend/front_end/source_frame/ImageView.js(68,5): error TS2322: Type '(ToolbarSeparator | ToolbarText)[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarSeparator | ToolbarText' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSeparator' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSeparator' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarSeparator'. node_modules/chrome-devtools-frontend/front_end/source_frame/ImageView.js(105,36): error TS2339: Property 'bytesToString' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/source_frame/ImageView.js(128,49): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/source_frame/ImageView.js(131,11): error TS2555: Expected at least 2 arguments, but got 1. @@ -10761,11 +10879,11 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/JSONView.js(165,28) node_modules/chrome-devtools-frontend/front_end/source_frame/JSONView.js(170,23): error TS2339: Property 'setSearchRegex' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/source_frame/PreviewFactory.js(14,33): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/source_frame/ResourceSourceFrame.js(51,35): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/source_frame/ResourceSourceFrame.js(69,5): error TS2554: Expected 3 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(15,22): error TS2339: Property 'installGutter' does not exist on type 'CodeMirrorTextEditor'. +node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(18,24): error TS2587: JSDoc type 'TextEditorPositionHandle' circularly references itself. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(89,28): error TS2339: Property 'toggleLineClass' does not exist on type 'CodeMirrorTextEditor'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(110,20): error TS2694: Namespace 'Diff' has no exported member 'Diff'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(177,20): error TS2694: Namespace 'Diff' has no exported member 'Diff'. +node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(110,25): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. +node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(177,25): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(202,16): error TS2403: Subsequent variable declarations must have the same type. Variable 'lineNumber' must be of type 'any', but here has type 'number'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(206,41): error TS2339: Property 'diff' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(275,22): error TS2339: Property 'setGutterDecoration' does not exist on type 'CodeMirrorTextEditor'. @@ -10773,11 +10891,6 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(2 node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(283,22): error TS2339: Property 'setGutterDecoration' does not exist on type 'CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(284,22): error TS2339: Property 'toggleLineClass' does not exist on type 'CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceFrame.js(41,11): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourceFrame.js(115,5): error TS2322: Type 'ToolbarText[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourceFrame.js(115,5): error TS2322: Type 'ToolbarText[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarText' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarText' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarText'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceFrame.js(371,32): error TS2339: Property 'lowerBound' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceFrame.js(435,15): error TS2339: Property '__fromRegExpQuery' does not exist on type 'RegExp'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceFrame.js(459,15): error TS2339: Property '__fromRegExpQuery' does not exist on type 'RegExp'. @@ -10796,9 +10909,6 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.j node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(39,23): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(45,12): error TS2339: Property '_isHandlingMouseDownEvent' does not exist on type 'SourcesTextEditor'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(54,20): error TS2694: Namespace 'UI' has no exported member 'AutocompleteConfig'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(55,65): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(73,53): error TS2339: Property 'isSpaceChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(80,53): error TS2339: Property 'isSpaceChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(90,14): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'number', but here has type 'string'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(93,29): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(134,12): error TS2339: Property '_tokenHighlighter' does not exist on type 'CodeMirrorTextEditor'. @@ -10823,13 +10933,11 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.j node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(284,25): error TS2339: Property 'removeLineClass' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(285,25): error TS2339: Property 'removeLineClass' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(295,38): error TS2339: Property 'lineInfo' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(359,40): error TS2339: Property 'Indent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(360,25): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(361,25): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(363,25): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(364,25): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(373,23): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(392,72): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(393,27): error TS2339: Property 'replaceRange' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(409,25): error TS2339: Property 'operation' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(411,35): error TS2339: Property 'getCursor' does not exist on type 'CodeMirror'. @@ -10844,10 +10952,6 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.j node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(614,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(622,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(631,14): error TS2339: Property 'operation' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(639,40): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(670,40): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(714,40): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(729,40): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(764,24): error TS2339: Property 'removeLineClass' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(769,24): error TS2339: Property 'addLineClass' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(780,51): error TS2339: Property 'markText' does not exist on type 'CodeMirror'. @@ -10857,9 +10961,6 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.j node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(803,39): error TS2339: Property 'getSelections' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(809,26): error TS2339: Property 'addLineClass' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(821,33): error TS2339: Property 'getLine' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(822,63): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(823,72): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(824,59): error TS2339: Property 'isWord' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(829,24): error TS2339: Property 'removeOverlay' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(839,9): error TS2367: This condition will always return 'false' since the types 'void' and 'number' have no overlap. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(854,9): error TS1345: An expression of type 'void' cannot be tested for truthiness @@ -10868,11 +10969,9 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.j node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(873,9): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(873,9): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(873,33): error TS1345: An expression of type 'void' cannot be tested for truthiness -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(873,70): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(874,14): error TS2367: This condition will always return 'false' since the types 'void' and 'number' have no overlap. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(878,12): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(878,12): error TS1345: An expression of type 'void' cannot be tested for truthiness -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(878,46): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(878,71): error TS2367: This condition will always return 'true' since the types 'void' and 'string' have no overlap. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(887,22): error TS2339: Property 'addOverlay' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(39,35): error TS2555: Expected at least 2 arguments, but got 1. @@ -10882,8 +10981,6 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(73,28): node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(80,23): error TS2339: Property 'setSearchRegex' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(223,35): error TS2339: Property 'childElementCount' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(242,7): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. -node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(242,7): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. - Property 'after' is missing in type 'Node'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(290,24): error TS2339: Property 'tagName' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(296,31): error TS2339: Property 'attributes' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(305,20): error TS2339: Property 'childElementCount' does not exist on type 'Node'. @@ -10916,7 +11013,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/AdvancedSearchView.js(31 node_modules/chrome-devtools-frontend/front_end/sources/AdvancedSearchView.js(397,46): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(84,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(102,19): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. -node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(150,41): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(197,26): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(197,34): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(212,26): error TS2339: Property 'title' does not exist on type 'Element'. @@ -10928,7 +11024,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(266,25): er node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(288,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(292,25): error TS2339: Property 'setBezierText' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(315,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(327,32): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(333,40): error TS2694: Namespace 'UI.SuggestBox' has no exported member 'Suggestions'. node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(33,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(39,57): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -10999,6 +11094,7 @@ node_modules/chrome-devtools-frontend/front_end/sources/InplaceFormatterEditorAc node_modules/chrome-devtools-frontend/front_end/sources/InplaceFormatterEditorAction.js(18,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/InplaceFormatterEditorAction.js(46,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/InplaceFormatterEditorAction.js(68,22): error TS2694: Namespace 'Common' has no exported member 'Event'. +node_modules/chrome-devtools-frontend/front_end/sources/InplaceFormatterEditorAction.js(100,37): error TS2339: Property 'selection' does not exist on type 'Widget'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(32,27): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(33,46): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(34,34): error TS2555: Expected at least 2 arguments, but got 1. @@ -11027,10 +11123,8 @@ node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSid node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptCompilerPlugin.js(51,5): error TS2322: Type 'Timer' is not assignable to type 'number'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(60,50): error TS2345: Argument of type 'Event' is not assignable to parameter of type 'MouseEvent | KeyboardEvent'. Type 'Event' is not assignable to type 'KeyboardEvent'. + Property 'altKey' is missing in type 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(107,33): error TS2339: Property 'asParsedURL' does not exist on type 'string'. -node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(109,21): error TS2345: Argument of type 'ToolbarText' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarText' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarText'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(128,59): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(132,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(134,95): error TS2339: Property 'valuesArray' does not exist on type 'Map'. @@ -11098,8 +11192,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(1403,54): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(1425,56): error TS2339: Property 'valuesArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(1442,31): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(1450,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(1463,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptSourceFrame.js(1469,63): error TS2694: Namespace 'SourceFrame.SourcesTextEditor' has no exported member 'GutterClickEventData'. node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(87,21): error TS2339: Property '_boostOrder' does not exist on type 'TreeElement'. @@ -11156,9 +11248,7 @@ node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(876,22) node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(951,23): error TS2339: Property '_title' does not exist on type 'NavigatorTreeNode'. node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(952,19): error TS2339: Property 'parent' does not exist on type 'NavigatorTreeNode'. node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(1023,17): error TS2339: Property 'title' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(1024,28): error TS2345: Argument of type 'Element[]' is not assignable to parameter of type 'Icon[]'. - Type 'Element' is not assignable to type 'Icon'. - Property 'createdCallback' is missing in type 'Element'. +node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(1024,29): error TS2322: Type 'Element' is not assignable to type 'Icon'. node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(1045,26): error TS2339: Property 'draggable' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(1055,51): error TS2339: Property 'hasFocus' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(1190,14): error TS2339: Property 'parent' does not exist on type 'NavigatorTreeNode'. @@ -11189,10 +11279,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(1614,14 node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(1616,40): error TS2339: Property '_treeElement' does not exist on type 'NavigatorTreeNode'. node_modules/chrome-devtools-frontend/front_end/sources/NavigatorView.js(1679,47): error TS2339: Property 'hasFocus' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/ObjectEventListenersSidebarPane.js(11,48): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/ObjectEventListenersSidebarPane.js(24,5): error TS2322: Type 'ToolbarButton[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarButton'. node_modules/chrome-devtools-frontend/front_end/sources/ObjectEventListenersSidebarPane.js(84,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/OutlineQuickOpen.js(32,52): error TS2694: Namespace 'Formatter.FormatterWorkerPool' has no exported member 'OutlineItem'. node_modules/chrome-devtools-frontend/front_end/sources/OutlineQuickOpen.js(118,14): error TS2555: Expected at least 2 arguments, but got 1. @@ -11211,14 +11297,10 @@ node_modules/chrome-devtools-frontend/front_end/sources/ScriptFormatterEditorAct node_modules/chrome-devtools-frontend/front_end/sources/ScriptFormatterEditorAction.js(28,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/ScriptFormatterEditorAction.js(61,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/ScriptFormatterEditorAction.js(85,22): error TS2694: Namespace 'Common' has no exported member 'Event'. +node_modules/chrome-devtools-frontend/front_end/sources/ScriptFormatterEditorAction.js(105,35): error TS2339: Property 'selection' does not exist on type 'Widget'. node_modules/chrome-devtools-frontend/front_end/sources/SimpleHistoryManager.js(37,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sources/SnippetsPlugin.js(41,39): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/SnippetsPlugin.js(41,73): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/SnippetsPlugin.js(43,5): error TS2322: Type 'ToolbarToggle[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. -node_modules/chrome-devtools-frontend/front_end/sources/SnippetsPlugin.js(43,5): error TS2322: Type 'ToolbarToggle[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarToggle'. node_modules/chrome-devtools-frontend/front_end/sources/SourceFormatter.js(48,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/SourceFormatter.js(55,32): error TS2339: Property 'remove' does not exist on type 'Map; formatData: SourceFormatData; }>'. node_modules/chrome-devtools-frontend/front_end/sources/SourceFormatter.js(67,32): error TS2339: Property 'remove' does not exist on type 'Map; formatData: SourceFormatData; }>'. @@ -11240,23 +11322,11 @@ node_modules/chrome-devtools-frontend/front_end/sources/SourceMapNamesResolver.j node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(51,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(109,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(145,17): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(149,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(189,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(211,19): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(214,39): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(216,39): error TS2345: Argument of type 'ToolbarSeparator' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSeparator' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(217,46): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(221,39): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(224,17): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(227,37): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(272,63): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(274,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(293,44): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(307,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/SourcesNavigator.js(308,41): error TS2555: Expected at least 2 arguments, but got 1. @@ -11267,24 +11337,15 @@ node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(35,26): node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(38,52): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(68,29): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(78,34): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(79,49): error TS2345: Argument of type 'ToolbarMenuButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(92,32): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(122,32): error TS2339: Property 'addEventListener' does not exist on type 'typeof extensionServer'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(131,30): error TS2551: Property '_instance' does not exist on type 'typeof SourcesPanel'. Did you mean 'instance'? node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(132,35): error TS2551: Property '_instance' does not exist on type 'typeof SourcesPanel'. Did you mean 'instance'? node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(133,55): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(149,58): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(151,61): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(153,62): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(208,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(227,52): error TS2339: Property '_instance' does not exist on type 'typeof WrapperView'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(242,40): error TS2339: Property '_instance' does not exist on type 'typeof WrapperView'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(257,7): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(257,7): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. +node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(257,7): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ...; }, insertBefore?: { ...'. Property 'appendApplicableItems' is missing in type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(277,20): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(289,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -11299,26 +11360,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(465,9): node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(550,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(596,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(689,30): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(691,36): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(694,38): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(695,38): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(696,38): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(697,38): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(699,38): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(700,38): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(701,38): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(705,36): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(709,36): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(717,17): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(795,13): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(798,13): error TS2555: Expected at least 2 arguments, but got 1. @@ -11333,11 +11374,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(963,21): node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(1011,45): error TS2339: Property 'offsetWidth' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(1078,60): error TS2339: Property 'sidebarPanes' does not exist on type 'typeof extensionServer'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(1093,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(1112,5): error TS2322: Type 'SourcesView' is not assignable to type '{ button(sourcesView: any & any): ToolbarButton; } & { button(sourcesView: any & any): ToolbarButton; }'. - Type 'SourcesView' is not assignable to type '{ button(sourcesView: any & any): ToolbarButton; }'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(1112,5): error TS2322: Type 'SourcesView' is not assignable to type '{ button(sourcesView: any & any): ToolbarButton; } & { button(sourcesView: any & any): ToolbarButton; }'. - Type 'SourcesView' is not assignable to type '{ button(sourcesView: any & any): ToolbarButton; }'. - Property 'button' is missing in type 'SourcesView'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(1290,38): error TS2339: Property '_instance' does not exist on type 'typeof WrapperView'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(1298,47): error TS2339: Property '_instance' does not exist on type 'typeof WrapperView'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesPanel.js(1298,93): error TS2339: Property '_instance' does not exist on type 'typeof WrapperView'. @@ -11349,12 +11385,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/SourcesSearchScope.js(16 node_modules/chrome-devtools-frontend/front_end/sources/SourcesSearchScope.js(163,19): error TS2339: Property 'mergeOrdered' does not exist on type 'string[]'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesSearchScope.js(163,51): error TS2339: Property 'naturalOrderComparator' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesSearchScope.js(257,29): error TS2339: Property 'mergeOrdered' does not exist on type 'any[]'. -node_modules/chrome-devtools-frontend/front_end/sources/SourcesView.js(36,70): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ button(sourcesView: any & any): ToolbarButton; } & { button(sourcesView: any & any): ToolbarButton; }'. - Type 'SourcesView' is not assignable to type '{ button(sourcesView: any & any): ToolbarButton; } & { button(sourcesView: any & any): ToolbarButton; }'. - Type 'SourcesView' is not assignable to type '{ button(sourcesView: any & any): ToolbarButton; }'. - Type 'this' is not assignable to type '{ button(sourcesView: any & any): ToolbarButton; }'. - Type 'SourcesView' is not assignable to type '{ button(sourcesView: any & any): ToolbarButton; }'. - Property 'button' is missing in type 'SourcesView'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesView.js(38,50): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesView.js(41,10): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/sources/SourcesView.js(55,36): error TS2694: Namespace 'Common.EventTarget' has no exported member 'EventDescriptor'. @@ -11386,7 +11416,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/TabbedEditorContainer.js node_modules/chrome-devtools-frontend/front_end/sources/TabbedEditorContainer.js(219,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/TabbedEditorContainer.js(237,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/TabbedEditorContainer.js(244,32): error TS2339: Property 'sourceSelectionChanged' does not exist on type 'typeof extensionServer'. -node_modules/chrome-devtools-frontend/front_end/sources/TabbedEditorContainer.js(342,7): error TS2554: Expected 3 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/TabbedEditorContainer.js(473,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/TabbedEditorContainer.js(485,18): error TS2339: Property 'remove' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/sources/TabbedEditorContainer.js(497,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -11400,6 +11429,12 @@ node_modules/chrome-devtools-frontend/front_end/sources/ThreadsSidebarPane.js(16 Type '(debuggerModel: DebuggerModel) => Element' is not assignable to type '(item: T) => Element'. Types of parameters 'debuggerModel' and 'item' are incompatible. Type 'T' is not assignable to type 'DebuggerModel'. +node_modules/chrome-devtools-frontend/front_end/sources/ThreadsSidebarPane.js(20,56): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'ThreadsSidebarPane' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(debuggerModel: DebuggerModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'debuggerModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'DebuggerModel'. node_modules/chrome-devtools-frontend/front_end/sources/ThreadsSidebarPane.js(38,25): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/ThreadsSidebarPane.js(39,31): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/ThreadsSidebarPane.js(49,33): error TS2555: Expected at least 2 arguments, but got 1. @@ -11420,30 +11455,22 @@ node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(469 node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(483,10): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(488,40): error TS2339: Property 'operation' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(496,32): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(511,24): error TS2339: Property 'pushAll' does not exist on type '({ item(): any & any; } & { item(): any & any; })[]'. +node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(511,24): error TS2339: Property 'pushAll' does not exist on type 'ToolbarItem[]'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(512,25): error TS2339: Property 'pushAll' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(547,31): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(550,22): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(552,39): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(603,22): error TS2339: Property '_messageBucket' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(604,35): error TS2339: Property 'createChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(624,42): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(638,38): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(652,23): error TS2339: Property 'toggleLineClass' does not exist on type 'CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(722,23): error TS2339: Property 'toggleLineClass' does not exist on type 'CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(728,21): error TS2339: Property 'toggleLineClass' does not exist on type 'CodeMirrorTextEditor'. -node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(733,32): error TS2339: Property '_messageLevelPriority' does not exist on type 'typeof Message'. -node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(744,41): error TS2339: Property '_messageLevelPriority' does not exist on type 'typeof Message'. -node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(745,38): error TS2339: Property '_messageLevelPriority' does not exist on type 'typeof Message'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(755,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(761,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(767,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarPane.js(46,44): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarPane.js(48,48): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarPane.js(66,5): error TS2322: Type 'ToolbarButton[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarButton'. node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarPane.js(97,25): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarPane.js(99,46): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarPane.js(100,38): error TS2555: Expected at least 2 arguments, but got 1. @@ -11473,7 +11500,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarP node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarPane.js(426,49): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarPane.js(428,24): error TS2339: Property 'deepElementFromPoint' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarPane.js(429,38): error TS2339: Property 'isSelfOrAncestor' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/sources/WatchExpressionsSidebarPane.js(430,7): error TS2554: Expected 3 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/WorkspaceMappingTip.js(28,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/WorkspaceMappingTip.js(39,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/WorkspaceMappingTip.js(107,25): error TS2339: Property 'asParsedURL' does not exist on type 'string'. @@ -11487,14 +11513,11 @@ node_modules/chrome-devtools-frontend/front_end/sources/WorkspaceMappingTip.js(1 node_modules/chrome-devtools-frontend/front_end/sources/WorkspaceMappingTip.js(171,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/WorkspaceMappingTip.js(173,63): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/WorkspaceMappingTip.js(174,16): error TS2339: Property 'createTextChild' does not exist on type 'Element'. +node_modules/chrome-devtools-frontend/front_end/sources/WorkspaceMappingTip.js(176,23): error TS2339: Property 'attachInfobars' does not exist on type 'Widget'. node_modules/chrome-devtools-frontend/front_end/sources/XHRBreakpointsSidebarPane.js(14,45): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/XHRBreakpointsSidebarPane.js(15,46): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/XHRBreakpointsSidebarPane.js(16,38): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/XHRBreakpointsSidebarPane.js(21,44): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/sources/XHRBreakpointsSidebarPane.js(34,5): error TS2322: Type 'ToolbarButton[]' is not assignable to type '({ item(): any & any; } & { item(): any & any; })[]'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarButton'. node_modules/chrome-devtools-frontend/front_end/sources/XHRBreakpointsSidebarPane.js(39,45): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/XHRBreakpointsSidebarPane.js(47,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/XHRBreakpointsSidebarPane.js(49,46): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -11527,6 +11550,14 @@ node_modules/chrome-devtools-frontend/front_end/sources_test_runner/BreakpointMa Property '_settings' is missing in type '{ get: () => any; set: (breakpoints: any) => void; }'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/BreakpointManagerTestRunner.js(333,12): error TS2339: Property 'setBreakpointCallback' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(125,28): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(170,17): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(171,15): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(212,15): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(218,15): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(224,15): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(230,15): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(396,25): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(426,25): error TS2339: Property 'sources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(483,26): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(515,23): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(644,15): error TS2339: Property 'runtime' does not exist on type 'Window'. @@ -11539,6 +11570,7 @@ node_modules/chrome-devtools-frontend/front_end/sources_test_runner/EditorTestRu node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(91,3): error TS2304: Cannot find name 'editor'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(94,23): error TS2304: Cannot find name 'editor'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(95,19): error TS2304: Cannot find name 'editor'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(97,34): error TS2339: Property 'sources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(114,23): error TS2304: Cannot find name 'editor'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(115,19): error TS2304: Cannot find name 'editor'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SourcesTestRunner.js(26,29): error TS2339: Property 'map' does not exist on type 'NodeListOf'. @@ -11680,8 +11712,8 @@ node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(363,62 node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(368,34): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(372,42): error TS2339: Property 'result' does not exist on type '{ response: RemoteObject; exceptionDetails: any; }'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(381,35): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(503,30): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(value: [any, any, any, any, any, any, any, any, any, any]) => [any, any, any, any, any, any, any, any, any, any] | PromiseLike<[any, any, any, any, any, any, any, any, any, any]>'. - Type 'Function' provides no match for the signature '(value: [any, any, any, any, any, any, any, any, any, any]): [any, any, any, any, any, any, any, any, any, any] | PromiseLike<[any, any, any, any, any, any, any, any, any, any]>'. +node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(503,30): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(value: any[]) => any[] | PromiseLike'. + Type 'Function' provides no match for the signature '(value: any[]): any[] | PromiseLike'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(641,59): error TS2339: Property 'testRunner' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(641,92): error TS2339: Property 'testRunner' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(642,3): error TS2322: Type '1' is not assignable to type 'boolean'. @@ -11725,19 +11757,7 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(270,27): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(356,16): error TS2339: Property 'addKeyMap' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(395,29): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(425,31): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(425,81): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(426,31): error TS2339: Property 'isUpperCase' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(426,82): error TS2339: Property 'isLowerCase' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(438,31): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(438,81): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(439,31): error TS2339: Property 'isUpperCase' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(439,82): error TS2339: Property 'isLowerCase' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(449,60): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(461,61): error TS2339: Property 'isSpaceChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(466,29): error TS2339: Property 'isStopChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(467,63): error TS2339: Property 'isStopChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(476,32): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(557,9): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(565,9): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(570,18): error TS2694: Namespace 'UI' has no exported member 'AutocompleteConfig'. @@ -11758,16 +11778,8 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1038,34): error TS2694: Namespace 'CodeMirror' has no exported member 'ChangeObject'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1052,23): error TS2339: Property 'valuesArray' does not exist on type 'Multimap'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1053,23): error TS2339: Property 'clear' does not exist on type 'Multimap'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1261,5): error TS2322: Type 'CodeMirrorPositionHandle' is not assignable to type '{ resolve(): { lineNumber: number; columnNumber: number; }; equal(positionHandle: any): boolean; }'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1261,5): error TS2322: Type 'CodeMirrorPositionHandle' is not assignable to type '{ resolve(): { lineNumber: number; columnNumber: number; }; equal(positionHandle: any): boolean; }'. Property '_codeMirror' does not exist on type '{ resolve(): { lineNumber: number; columnNumber: number; }; equal(positionHandle: any): boolean; }'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1280,21): error TS2339: Property 'autocomplete' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1283,21): error TS2339: Property 'undoLastSelection' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1286,21): error TS2339: Property 'selectNextOccurrence' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1289,21): error TS2339: Property 'moveCamelLeft' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1290,21): error TS2339: Property 'selectCamelLeft' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1293,21): error TS2339: Property 'moveCamelRight' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1294,21): error TS2339: Property 'selectCamelRight' does not exist on type 'typeof commands'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1301,31): error TS2339: Property 'listSelections' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1305,38): error TS2339: Property 'findMatchingBracket' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1313,14): error TS2339: Property 'setSelections' does not exist on type 'CodeMirror'. @@ -11784,8 +11796,6 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1392,35): error TS2339: Property 'getLineHandle' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1401,58): error TS2339: Property 'getLineNumber' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1451,22): error TS2339: Property 'execCommand' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1494,96): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1497,90): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1539,44): error TS2339: Property 'getLine' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1543,22): error TS2339: Property 'eachLine' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1543,69): error TS2339: Property 'lineCount' does not exist on type 'CodeMirror'. @@ -11793,6 +11803,7 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1551,68): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'number'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1563,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1569,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. +node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1571,9): error TS2502: 'positionHandle' is referenced directly or indirectly in its own type annotation. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1614,9): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1615,48): error TS2339: Property 'line' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1621,9): error TS1345: An expression of type 'void' cannot be tested for truthiness @@ -11823,8 +11834,6 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocomple node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(55,24): error TS2339: Property 'off' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(62,26): error TS2694: Namespace 'CodeMirror' has no exported member 'BeforeChangeObject'. node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(67,48): error TS2339: Property 'getLine' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(74,25): error TS2339: Property 'textToWords' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(91,25): error TS2339: Property 'textToWords' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(113,40): error TS2694: Namespace 'UI.SuggestBox' has no exported member 'Suggestions'. node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(135,34): error TS2694: Namespace 'CodeMirror' has no exported member 'ChangeObject'. node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(151,47): error TS2339: Property 'getLine' does not exist on type 'CodeMirror'. @@ -11853,28 +11862,10 @@ node_modules/chrome-devtools-frontend/front_end/text_utils/Text.js(122,16): erro node_modules/chrome-devtools-frontend/front_end/text_utils/Text.js(122,16): error TS2339: Property 'Position' does not exist on type 'typeof Text'. node_modules/chrome-devtools-frontend/front_end/text_utils/Text.js(160,42): error TS2339: Property 'lowerBound' does not exist on type 'number[]'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextRange.js(84,31): error TS2339: Property 'computeLineEndings' does not exist on type 'string'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(35,3): error TS2322: Type '{ isStopChar: (char: string) => boolean; isWordChar: (char: string) => boolean; isSpaceChar: (char: string) => boolean; isWord: (word: string) => boolean; isOpeningBraceChar: (char: string) => boolean; ... 6 more ...; splitStringByRegexes(text: string, regexes: RegExp[]): { ...; }[]; }' is not assignable to type 'typeof TextUtils'. - Object literal may only specify known properties, and 'isStopChar' does not exist in type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(45,33): error TS2339: Property 'isStopChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(45,74): error TS2339: Property 'isSpaceChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(53,32): error TS2339: Property '_SpaceCharRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(62,32): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(89,32): error TS2339: Property 'isOpeningBraceChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(89,80): error TS2339: Property 'isClosingBraceChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(118,61): error TS2339: Property 'isSpaceChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(201,38): error TS2694: Namespace 'TextUtils.FilterParser' has no exported member 'ParsedFilter'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(202,39): error TS2694: Namespace 'TextUtils.FilterParser' has no exported member 'ParsedFilter'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(210,46): error TS2694: Namespace 'TextUtils.FilterParser' has no exported member 'ParsedFilter'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(213,43): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(214,27): error TS2339: Property '_keyValueFilterRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(214,69): error TS2339: Property '_regexFilterRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(215,27): error TS2339: Property '_textFilterRegex' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(243,24): error TS2339: Property 'ParsedFilter' does not exist on type 'typeof FilterParser'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(245,21): error TS2339: Property '_keyValueFilterRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(246,21): error TS2339: Property '_regexFilterRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(247,21): error TS2339: Property '_textFilterRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(248,21): error TS2339: Property '_SpaceCharRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(253,21): error TS2339: Property 'Indent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(340,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(59,42): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(75,9): error TS2555: Expected at least 2 arguments, but got 1. @@ -11902,9 +11893,6 @@ node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(334,54 node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(371,43): error TS2339: Property 'withThousandsSeparator' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(379,28): error TS2339: Property 'backgroundColor' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(380,28): error TS2339: Property 'borderColor' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(383,45): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarSettingCheckbox'. node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(384,40): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(394,50): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(414,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -11916,11 +11904,6 @@ node_modules/chrome-devtools-frontend/front_end/timeline/EventsTimelineTreeView. node_modules/chrome-devtools-frontend/front_end/timeline/EventsTimelineTreeView.js(95,34): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/EventsTimelineTreeView.js(158,73): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/EventsTimelineTreeView.js(160,24): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/EventsTimelineTreeView.js(163,31): error TS2345: Argument of type 'ToolbarComboBox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarComboBox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/EventsTimelineTreeView.js(176,33): error TS2345: Argument of type 'ToolbarCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarCheckbox' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarCheckbox'. node_modules/chrome-devtools-frontend/front_end/timeline/EventsTimelineTreeView.js(183,56): error TS2339: Property 'value' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceModel.js(157,25): error TS2304: Cannot find name 'FileError'. node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(26,46): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -11958,6 +11941,12 @@ node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(4 node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(517,43): error TS2694: Namespace 'Timeline.PerformanceMonitor' has no exported member 'ChartInfo'. node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(526,27): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(539,43): error TS2694: Namespace 'Timeline.PerformanceMonitor' has no exported member 'ChartInfo'. +node_modules/chrome-devtools-frontend/front_end/timeline/TimelineController.js(28,59): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Type 'TimelineController' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. + Types of property 'modelAdded' are incompatible. + Type '(cpuProfilerModel: CPUProfilerModel) => void' is not assignable to type '(model: T) => void'. + Types of parameters 'cpuProfilerModel' and 'model' are incompatible. + Type 'T' is not assignable to type 'CPUProfilerModel'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineController.js(39,43): error TS2694: Namespace 'Timeline.TimelineController' has no exported member 'RecordingOptions'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineController.js(44,64): error TS2339: Property 'traceProviders' does not exist on type 'typeof extensionServer'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineController.js(137,24): error TS2694: Namespace 'Protocol' has no exported member 'Profiler'. @@ -11987,7 +11976,6 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.j node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(204,36): error TS2339: Property '_overviewIndex' does not exist on type 'TimelineCategory'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(246,68): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(248,81): error TS2339: Property '_overviewIndex' does not exist on type 'TimelineCategory'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(384,7): error TS2322: Type 'Promise HTMLImageElement>' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(384,7): error TS2322: Type 'Promise HTMLImageElement>' is not assignable to type 'Promise'. Type 'new (width?: number, height?: number) => HTMLImageElement' is not assignable to type 'HTMLImageElement'. Property 'align' is missing in type 'new (width?: number, height?: number) => HTMLImageElement'. @@ -12098,16 +12086,6 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineHistoryManager. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineHistoryManager.js(432,39): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineLayersView.js(66,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineLoader.js(43,14): error TS2339: Property '_reportErrorAndCancelLoading' does not exist on type 'typeof TimelineLoader'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineLoader.js(45,5): error TS2322: Type 'TimelineLoader' is not assignable to type '{ loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; } & { loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; }'. - Type 'TimelineLoader' is not assignable to type '{ loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineLoader.js(45,5): error TS2322: Type 'TimelineLoader' is not assignable to type '{ loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; } & { loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; }'. - Type 'TimelineLoader' is not assignable to type '{ loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; }'. - Property 'loadingStarted' is missing in type 'TimelineLoader'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineLoader.js(56,5): error TS2322: Type 'TimelineLoader' is not assignable to type '{ loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; } & { loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; }'. - Type 'TimelineLoader' is not assignable to type '{ loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineLoader.js(56,5): error TS2322: Type 'TimelineLoader' is not assignable to type '{ loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; } & { loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; }'. - Type 'TimelineLoader' is not assignable to type '{ loadingStarted(): void; loadingProgress(progress?: number): void; processingStarted(): void; loadingComplete(tracingModel: TracingModel): void; }'. - Property 'loadingStarted' is missing in type 'TimelineLoader'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineLoader.js(91,43): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineLoader.js(118,41): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineLoader.js(137,54): error TS2694: Namespace 'SDK.TracingManager' has no exported member 'EventPayload'. @@ -12126,46 +12104,16 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(111,60 node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(131,32): error TS2339: Property 'addEventListener' does not exist on type 'typeof extensionServer'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(140,57): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(168,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(206,42): error TS2345: Argument of type 'ToolbarSettingCheckbox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarSettingCheckbox'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(207,5): error TS2322: Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(207,5): error TS2322: Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingCheckbox' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarSettingCheckbox'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(212,42): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(213,42): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(214,46): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(216,42): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(219,45): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(221,45): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(224,42): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(225,42): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(230,44): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarButton'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(237,67): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(241,62): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(245,42): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(251,42): error TS2345: Argument of type 'ToolbarSettingToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSettingToggle' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarSettingToggle'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(257,67): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(274,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(277,9): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(284,41): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(286,48): error TS2345: Argument of type 'ToolbarComboBox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarComboBox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(289,37): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(291,44): error TS2345: Argument of type 'ToolbarComboBox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarComboBox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(298,23): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(340,33): error TS2339: Property 'remove' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(362,37): error TS2339: Property 'toISO8601Compact' does not exist on type 'Date'. @@ -12194,7 +12142,6 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(732,42 node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(739,35): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(773,35): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(800,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(814,11): error TS2367: This condition will always return 'true' since the types '{ recordingProgress(usage: number): void; } & { recordingProgress(usage: number): void; }' and 'TimelineController' have no overlap. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(850,20): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(878,29): error TS2339: Property 'upperBound' does not exist on type 'Event[]'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(1029,24): error TS2339: Property 'ModelSelectionData' does not exist on type 'typeof TimelinePanel'. @@ -12213,15 +12160,9 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(1224,2 node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(1234,22): error TS2339: Property 'focus' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelinePanel.js(1291,61): error TS2339: Property 'decodeURIComponent' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(65,58): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(133,31): error TS2345: Argument of type 'ToolbarComboBox' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarComboBox' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(134,46): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(136,31): error TS2345: Argument of type 'ToolbarInput' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarInput' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarInput'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(162,76): error TS2339: Property 'value' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(173,52): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(280,5): error TS2322: Type 'TopDownRootNode' is not assignable to type 'Node'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(280,5): error TS2322: Type 'TopDownRootNode' is not assignable to type 'Node'. Property 'id' is missing in type 'TopDownRootNode'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(286,40): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. @@ -12238,22 +12179,17 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(590 node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(696,14): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(698,14): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(712,24): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(717,9): error TS2322: Type '{ name: string; color: string; }' is not assignable to type '{ name: string; color: string; icon: Element; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(717,9): error TS2322: Type '{ name: string; color: string; }' is not assignable to type '{ name: string; color: string; icon: Element; }'. Property 'icon' is missing in type '{ name: string; color: string; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(727,9): error TS2322: Type '{ name: string; color: string; }' is not assignable to type '{ name: string; color: string; icon: Element; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(727,9): error TS2322: Type '{ name: string; color: string; }' is not assignable to type '{ name: string; color: string; icon: Element; }'. Property 'icon' is missing in type '{ name: string; color: string; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(731,13): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(733,9): error TS2322: Type '{ name: any; color: string; }' is not assignable to type '{ name: string; color: string; icon: Element; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(733,9): error TS2322: Type '{ name: any; color: string; }' is not assignable to type '{ name: string; color: string; icon: Element; }'. Property 'icon' is missing in type '{ name: any; color: string; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(743,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'name' must be of type 'any', but here has type 'string'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(753,91): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(754,9): error TS2322: Type '{ name: any; color: string; }' is not assignable to type '{ name: string; color: string; icon: Element; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(754,9): error TS2322: Type '{ name: any; color: string; }' is not assignable to type '{ name: string; color: string; icon: Element; }'. Property 'icon' is missing in type '{ name: any; color: string; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(759,5): error TS2322: Type '{ name: string; color: string; }' is not assignable to type '{ name: string; color: string; icon: Element; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(759,5): error TS2322: Type '{ name: string; color: string; }' is not assignable to type '{ name: string; color: string; icon: Element; }'. Property 'icon' is missing in type '{ name: string; color: string; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(770,15): error TS2555: Expected at least 2 arguments, but got 1. @@ -12267,13 +12203,10 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(777 node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(779,61): error TS2345: Argument of type '{ label: any; value: string; }[]' is not assignable to parameter of type '{ value: string; label: string; title: string; default: boolean; }[]'. Type '{ label: any; value: string; }' is not assignable to type '{ value: string; label: string; title: string; default: boolean; }'. Property 'title' is missing in type '{ label: any; value: string; }'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(781,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(781,77): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(871,25): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(896,25): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(910,25): error TS2339: Property 'asParsedURL' does not exist on type 'string'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(931,5): error TS2554: Expected 3 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(1019,31): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(1020,26): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js(1022,56): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. @@ -12630,6 +12563,7 @@ node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineJSProfile node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineJSProfile.js(31,50): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineJSProfile.js(31,89): error TS2339: Property 'depth' does not exist on type 'CPUProfileNode'. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineJSProfile.js(33,38): error TS2322: Type 'ProfileNode' is not assignable to type 'CPUProfileNode'. + Property 'positionTicks' is missing in type 'ProfileNode'. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineJSProfile.js(34,50): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineJSProfile.js(51,26): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineJSProfile.js(52,26): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -12691,6 +12625,7 @@ node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineModel.js( node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineModel.js(1811,25): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineModel.js(1819,32): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineModelFilter.js(43,22): error TS1110: Type expected. +node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js(72,15): error TS2587: JSDoc type 'TopDownNode' circularly references itself. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js(74,26): error TS2502: 'parent' is referenced directly or indirectly in its own type annotation. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js(168,31): error TS2345: Argument of type 'string | symbol' is not assignable to parameter of type 'string'. Type 'symbol' is not assignable to type 'string'. @@ -12701,7 +12636,6 @@ node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTr Types of property 'parent' are incompatible. Type 'TopDownRootNode | BottomUpRootNode' is not assignable to type 'Node'. Type 'TopDownRootNode' is not assignable to type 'Node'. -node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js(413,5): error TS2322: Type 'this' is not assignable to type 'Node'. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js(413,5): error TS2322: Type 'this' is not assignable to type 'Node'. Type 'GroupNode' is not assignable to type 'Node'. Types of property 'parent' are incompatible. @@ -12753,6 +12687,7 @@ node_modules/chrome-devtools-frontend/front_end/ui/Context.js(73,30): error TS23 node_modules/chrome-devtools-frontend/front_end/ui/Context.js(77,33): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/ui/Context.js(86,45): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/ui/Context.js(101,16): error TS2339: Property 'runtime' does not exist on type 'Window'. +node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(36,15): error TS2587: JSDoc type 'ContextMenu' circularly references itself. node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(42,15): error TS2502: 'contextMenu' is referenced directly or indirectly in its own type annotation. node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(81,41): error TS2694: Namespace 'InspectorFrontendHostAPI' has no exported member 'ContextMenuDescriptor'. node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(87,18): error TS2339: Property '_customElement' does not exist on type 'ContextMenuItem'. @@ -12773,7 +12708,6 @@ node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(453,57): error node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(457,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(483,37): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(491,32): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(519,32): error TS2502: 'contextMenu' is referenced directly or indirectly in its own type annotation. node_modules/chrome-devtools-frontend/front_end/ui/Dialog.js(35,25): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/Dialog.js(42,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/Dialog.js(55,24): error TS2339: Property '_instance' does not exist on type 'typeof Dialog'. @@ -12911,17 +12845,12 @@ node_modules/chrome-devtools-frontend/front_end/ui/InplaceEditor.js(133,22): err node_modules/chrome-devtools-frontend/front_end/ui/InplaceEditor.js(134,33): error TS2339: Property 'shiftKey' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/InplaceEditor.js(185,18): error TS2339: Property 'Controller' does not exist on type 'typeof InplaceEditor'. node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(53,50): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(55,61): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarButton'. node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(69,40): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(80,24): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(92,51): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(116,7): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. -node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(116,7): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. +node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(116,7): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ...; }, insertBefore?: { ...'. Property 'appendApplicableItems' is missing in type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }'. -node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(118,7): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. -node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(118,7): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. +node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(118,7): error TS2322: Type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ...; }, insertBefore?: { ...'. Property 'appendApplicableItems' is missing in type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }'. node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(247,73): error TS2339: Property 'altKey' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/InspectorView.js(247,89): error TS2339: Property 'shiftKey' does not exist on type 'Event'. @@ -12981,11 +12910,8 @@ node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(17,18): error T node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(127,14): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(129,28): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(133,43): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(135,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(137,45): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(139,31): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. +node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(157,20): error TS2339: Property 'focus' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(203,32): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(203,58): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(241,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -13029,18 +12955,11 @@ node_modules/chrome-devtools-frontend/front_end/ui/RootView.js(36,20): error TS2 node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(49,25): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(50,56): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(55,54): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(57,44): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarToggle'. node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(65,44): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(76,47): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(81,47): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(89,45): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(97,56): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(100,33): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(107,33): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(111,29): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(117,29): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/SearchableView.js(118,32): error TS2339: Property 'disabled' does not exist on type 'Element'. @@ -13306,7 +13225,6 @@ node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(241,23): error node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(242,21): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(249,19): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(268,68): error TS2345: Argument of type 'Event' is not assignable to parameter of type 'KeyboardEvent'. - Property 'altKey' is missing in type 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(269,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(273,19): error TS2339: Property 'key' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(299,19): error TS2339: Property 'ctrlKey' does not exist on type 'Event'. @@ -13324,7 +13242,6 @@ node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(592,35): error node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(601,32): error TS2339: Property 'isAncestor' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(610,54): error TS2339: Property 'isAncestor' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(622,35): error TS2339: Property 'getComponentSelection' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(627,7): error TS2322: Type 'ChildNode' is not assignable to type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(627,7): error TS2322: Type 'ChildNode' is not assignable to type 'Element'. Property 'assignedSlot' is missing in type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(43,50): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -13332,28 +13249,10 @@ node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(48,45): error TS23 node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(75,24): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(115,26): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(134,47): error TS2339: Property 'boxInWindow' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(151,38): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(257,28): error TS2345: Argument of type 'ToolbarSeparator' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSeparator' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarSeparator'. -node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(261,28): error TS2345: Argument of type 'ToolbarSeparator' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarSeparator' is not assignable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(268,28): error TS2345: Argument of type 'ToolbarText' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarText' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarText'. -node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(318,56): error TS2339: Property 'peekLast' does not exist on type '({ item(): any & any; } & { item(): any & any; })[]'. +node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(246,10): error TS2339: Property '_toolbar' does not exist on type 'ToolbarItem'. +node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(273,19): error TS2339: Property '_toolbar' does not exist on type 'ToolbarItem'. +node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(318,56): error TS2339: Property 'peekLast' does not exist on type 'ToolbarItem[]'. node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(328,27): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(343,36): error TS2352: Conversion of type 'ToolbarSeparator' to type '{ item(): any & any; } & { item(): any & any; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Type 'ToolbarSeparator' is not comparable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(343,36): error TS2352: Conversion of type 'ToolbarSeparator' to type '{ item(): any & any; } & { item(): any & any; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Type 'ToolbarSeparator' is not comparable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarSeparator'. -node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(346,17): error TS2352: Conversion of type 'ToolbarToggle' to type '{ item(): any & any; } & { item(): any & any; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Type 'ToolbarToggle' is not comparable to type '{ item(): any & any; }'. -node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(346,17): error TS2352: Conversion of type 'ToolbarToggle' to type '{ item(): any & any; } & { item(): any & any; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Type 'ToolbarToggle' is not comparable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarToggle'. node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(405,53): error TS2339: Property '_toolbar' does not exist on type 'ToolbarItem'. node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(405,70): error TS2339: Property '_toolbar' does not exist on type 'ToolbarItem'. node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(412,18): error TS2339: Property 'disabled' does not exist on type 'Element'. @@ -13547,15 +13446,13 @@ node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(2020,30): error TS node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(2024,50): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(2025,50): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(2027,15): error TS2339: Property 'consume' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(2046,29): error TS2345: Argument of type 'ToolbarToggle' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarToggle' is not assignable to type '{ item(): any & any; }'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(11,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/ui/View.js(16,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/ui/View.js(21,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/ui/View.js(26,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/ui/View.js(31,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/ui/View.js(36,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. -node_modules/chrome-devtools-frontend/front_end/ui/View.js(195,47): error TS2352: Conversion of type 'Widget' to type '{ toolbarItems(): ({ item(): any & any; } & { item(): any & any; })[]; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. +node_modules/chrome-devtools-frontend/front_end/ui/View.js(195,47): error TS2352: Conversion of type 'Widget' to type '{ toolbarItems(): ToolbarItem[]; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property 'toolbarItems' is missing in type 'Widget'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(244,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/ui/View.js(254,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -13563,44 +13460,39 @@ node_modules/chrome-devtools-frontend/front_end/ui/View.js(263,1): error TS8022: node_modules/chrome-devtools-frontend/front_end/ui/View.js(267,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/ui/View.js(282,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/ui/View.js(297,32): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/ui/View.js(299,41): error TS2345: Argument of type 'ProvidedView' is not assignable to parameter of type '{ viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { item(): any & any; })[]>; widget(): Promise; disposeView(): void; }'. - Property '_extension' does not exist on type '{ viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { item(): any & any; })[]>; widget(): Promise; disposeView(): void; }'. +node_modules/chrome-devtools-frontend/front_end/ui/View.js(299,41): error TS2345: Argument of type 'ProvidedView' is not assignable to parameter of type '{ viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise; widget(): Promise; disposeView(): void; }'. + Property '_extension' does not exist on type '{ viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise; widget(): Promise; disposeView(): void; }'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(326,21): error TS2339: Property 'showView' does not exist on type '_Location'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(371,23): error TS2339: Property 'showView' does not exist on type '_Location'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(383,35): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/ui/View.js(401,5): error TS2322: Type '_TabbedLocation' is not assignable to type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(401,5): error TS2322: Type '_TabbedLocation' is not assignable to type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }'. Property '_tabbedPane' does not exist on type '{ tabbedPane(): TabbedPane; enableMoreTabsButton(): void; }'. -node_modules/chrome-devtools-frontend/front_end/ui/View.js(411,5): error TS2322: Type '_StackLocation' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. -node_modules/chrome-devtools-frontend/front_end/ui/View.js(411,5): error TS2322: Type '_StackLocation' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. - Property '_vbox' does not exist on type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise<({ item(): any & any; } & { ...; })[]>; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ....'. +node_modules/chrome-devtools-frontend/front_end/ui/View.js(411,5): error TS2322: Type '_StackLocation' is not assignable to type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ...; }, insertBefore?: { ...'. + Property '_vbox' does not exist on type '{ appendApplicableItems(locationName: string): void; appendView(view: { viewId(): string; title(): string; isCloseable(): boolean; isTransient(): boolean; toolbarItems(): Promise; widget(): Promise<...>; disposeView(): void; }, insertBefore?: { ...; }): void; showView(view: { ...; }, insertBefore?: { ...'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(440,18): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(454,38): error TS2339: Property 'hasFocus' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/ui/View.js(461,44): error TS2345: Argument of type '(Promise | Promise<({ item(): any & any; } & { item(): any & any; })[]>)[]' is not assignable to parameter of type 'Iterable>'. +node_modules/chrome-devtools-frontend/front_end/ui/View.js(461,44): error TS2345: Argument of type '(Promise | Promise)[]' is not assignable to parameter of type 'Iterable>'. Types of property '[Symbol.iterator]' are incompatible. - Type '() => IterableIterator | Promise<({ item(): any & any; } & { item(): any & any; })[]>>' is not assignable to type '() => Iterator>'. - Type 'IterableIterator | Promise<({ item(): any & any; } & { item(): any & any; })[]>>' is not assignable to type 'Iterator>'. + Type '() => IterableIterator | Promise>' is not assignable to type '() => Iterator>'. + Type 'IterableIterator | Promise>' is not assignable to type 'Iterator>'. Types of property 'next' are incompatible. - Type '{ (value?: any): IteratorResult | Promise<({ item(): any & any; } & { item(): any & any; })[]>>; (value?: any): IteratorResult | Promise<({ item(): any & any; } & { item(): any & any; })[]>>; }' is not assignable to type '{ (value?: any): IteratorResult>; (value?: any): IteratorResult>; }'. - Type 'IteratorResult | Promise<({ item(): any & any; } & { item(): any & any; })[]>>' is not assignable to type 'IteratorResult>'. - Type 'Promise | Promise<({ item(): any & any; } & { item(): any & any; })[]>' is not assignable to type 'void | PromiseLike'. - Type 'Promise<({ item(): any & any; } & { item(): any & any; })[]>' is not assignable to type 'void | PromiseLike'. - Type 'Promise<({ item(): any & any; } & { item(): any & any; })[]>' is not assignable to type 'PromiseLike'. + Type '{ (value?: any): IteratorResult | Promise>; (value?: any): IteratorResult | Promise>; }' is not assignable to type '{ (value?: any): IteratorResult>; (value?: any): IteratorResult>; }'. + Type 'IteratorResult | Promise>' is not assignable to type 'IteratorResult>'. + Type 'Promise | Promise' is not assignable to type 'void | PromiseLike'. + Type 'Promise' is not assignable to type 'void | PromiseLike'. + Type 'Promise' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. - Type '(onfulfilled?: (value: ({ item(): any & any; } & { item(): any & any; })[]) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike<...>) => Promise<...>' is not assignable to type '(onfulfilled?: (value: void) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => PromiseLike'. + Type '(onfulfilled?: (value: ToolbarItem[]) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise' is not assignable to type '(onfulfilled?: (value: void) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => PromiseLike'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. - Type '({ item(): any & any; } & { item(): any & any; })[]' is not assignable to type 'void'. + Type 'ToolbarItem[]' is not assignable to type 'void'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(495,24): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(496,24): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(501,25): error TS2339: Property 'createChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/ui/View.js(520,44): error TS2345: Argument of type '(Promise | Promise<({ item(): any & any; } & { item(): any & any; })[]>)[]' is not assignable to parameter of type 'Iterable>'. +node_modules/chrome-devtools-frontend/front_end/ui/View.js(520,44): error TS2345: Argument of type '(Promise | Promise)[]' is not assignable to parameter of type 'Iterable>'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(556,36): error TS2339: Property 'keyCode' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(558,22): error TS2339: Property 'key' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(560,22): error TS2339: Property 'key' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/ui/View.js(659,54): error TS2345: Argument of type 'ToolbarMenuButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. - Type 'ToolbarMenuButton' is not assignable to type '{ item(): any & any; }'. - Property 'item' is missing in type 'ToolbarMenuButton'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(702,19): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/View.js(793,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/View.js(802,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -13778,15 +13670,15 @@ node_modules/chrome-devtools-frontend/front_end/workspace/Workspace.js(243,25): Type 'ProjectStore' is not comparable to type '{ workspace(): Workspace; id(): string; type(): string; isServiceProject(): boolean; displayName(): string; requestMetadata(uiSourceCode: UISourceCode): Promise; ... 17 more ...; uiSourceCodes(): UISourceCode[]; }'. Property 'isServiceProject' is missing in type 'ProjectStore'. node_modules/chrome-devtools-frontend/front_end/workspace/Workspace.js(432,27): error TS2339: Property 'valuesArray' does not exist on type 'Map; ... 17 more ...; uiSourceCodes(): UISourceCode[]; }>'. -node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(30,30): error TS2694: Namespace 'Diff' has no exported member 'Diff'. +node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(30,35): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(38,31): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(47,31): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(72,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(80,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(88,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(96,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(236,30): error TS2694: Namespace 'Diff' has no exported member 'Diff'. -node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(260,30): error TS2694: Namespace 'Diff' has no exported member 'Diff'. +node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(236,35): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. +node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(260,35): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(301,36): error TS2339: Property '_instance' does not exist on type 'typeof WorkspaceDiff'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(302,33): error TS2339: Property '_instance' does not exist on type 'typeof WorkspaceDiff'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(303,38): error TS2339: Property '_instance' does not exist on type 'typeof WorkspaceDiff'. diff --git a/tests/baselines/reference/user/create-react-app.log b/tests/baselines/reference/user/create-react-app.log index a7dc1694a90..537770fe818 100644 --- a/tests/baselines/reference/user/create-react-app.log +++ b/tests/baselines/reference/user/create-react-app.log @@ -15,9 +15,9 @@ packages/babel-preset-react-app/index.js(123,17): error TS2307: Cannot find modu packages/babel-preset-react-app/index.js(130,17): error TS2307: Cannot find module '@babel/plugin-transform-regenerator'. packages/babel-preset-react-app/index.js(137,15): error TS2307: Cannot find module '@babel/plugin-syntax-dynamic-import'. packages/babel-preset-react-app/index.js(140,17): error TS2307: Cannot find module 'babel-plugin-transform-dynamic-import'. -packages/confusing-browser-globals/test.js(14,1): error TS2304: Cannot find name 'it'. +packages/confusing-browser-globals/test.js(14,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/confusing-browser-globals/test.js(15,3): error TS2304: Cannot find name 'expect'. -packages/confusing-browser-globals/test.js(18,1): error TS2304: Cannot find name 'it'. +packages/confusing-browser-globals/test.js(18,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/confusing-browser-globals/test.js(19,3): error TS2304: Cannot find name 'expect'. packages/create-react-app/createReactApp.js(37,37): error TS2307: Cannot find module 'validate-npm-package-name'. packages/create-react-app/createReactApp.js(47,24): error TS2307: Cannot find module 'tar-pack'. @@ -35,18 +35,18 @@ packages/react-dev-utils/FileSizeReporter.js(16,24): error TS2307: Cannot find m packages/react-dev-utils/WebpackDevServerUtils.js(9,25): error TS2307: Cannot find module 'address'. packages/react-dev-utils/WebpackDevServerUtils.js(14,24): error TS2307: Cannot find module 'detect-port-alt'. packages/react-dev-utils/WebpackDevServerUtils.js(15,24): error TS2307: Cannot find module 'is-root'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(12,1): error TS2304: Cannot find name 'describe'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(13,3): error TS2304: Cannot find name 'it'. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(12,1): error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(13,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/react-dev-utils/__tests__/ignoredFiles.test.js(18,5): error TS2304: Cannot find name 'expect'. packages/react-dev-utils/__tests__/ignoredFiles.test.js(19,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(22,3): error TS2304: Cannot find name 'it'. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(22,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/react-dev-utils/__tests__/ignoredFiles.test.js(26,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(29,3): error TS2304: Cannot find name 'it'. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(29,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/react-dev-utils/__tests__/ignoredFiles.test.js(36,5): error TS2304: Cannot find name 'expect'. packages/react-dev-utils/__tests__/ignoredFiles.test.js(37,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(40,3): error TS2304: Cannot find name 'it'. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(40,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/react-dev-utils/__tests__/ignoredFiles.test.js(46,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(49,3): error TS2304: Cannot find name 'it'. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(49,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/react-dev-utils/__tests__/ignoredFiles.test.js(53,5): error TS2304: Cannot find name 'expect'. packages/react-dev-utils/browsersHelper.js(9,30): error TS2307: Cannot find module 'browserslist'. packages/react-dev-utils/browsersHelper.js(13,23): error TS2307: Cannot find module 'pkg-up'. diff --git a/tests/baselines/reference/user/debug.log b/tests/baselines/reference/user/debug.log index f15ca0b273b..da4e47f9207 100644 --- a/tests/baselines/reference/user/debug.log +++ b/tests/baselines/reference/user/debug.log @@ -1,48 +1,90 @@ Exit Code: 1 Standard output: -node_modules/debug/src/browser.js(13,41): error TS2304: Cannot find name 'chrome'. -node_modules/debug/src/browser.js(14,41): error TS2304: Cannot find name 'chrome'. -node_modules/debug/src/browser.js(15,21): error TS2304: Cannot find name 'chrome'. -node_modules/debug/src/browser.js(48,47): error TS2339: Property 'process' does not exist on type 'Window'. -node_modules/debug/src/browser.js(48,65): error TS2339: Property 'process' does not exist on type 'Window'. -node_modules/debug/src/browser.js(59,139): error TS2551: Property 'WebkitAppearance' does not exist on type 'CSSStyleDeclaration'. Did you mean 'webkitAppearance'? -node_modules/debug/src/browser.js(61,73): error TS2339: Property 'firebug' does not exist on type 'Console'. -node_modules/debug/src/browser.js(187,13): error TS2304: Cannot find name 'LocalStorage'. -node_modules/debug/src/debug.js(25,1): error TS2323: Cannot redeclare exported variable 'names'. -node_modules/debug/src/debug.js(26,1): error TS2323: Cannot redeclare exported variable 'skips'. -node_modules/debug/src/debug.js(46,13): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. -node_modules/debug/src/debug.js(47,57): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. -node_modules/debug/src/debug.js(51,18): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(51,50): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(75,10): error TS2339: Property 'diff' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. -node_modules/debug/src/debug.js(76,10): error TS2339: Property 'prev' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. -node_modules/debug/src/debug.js(77,10): error TS2339: Property 'curr' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. -node_modules/debug/src/debug.js(112,13): error TS2551: Property 'formatArgs' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. Did you mean 'formatters'? -node_modules/debug/src/debug.js(114,23): error TS2339: Property 'log' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. -node_modules/debug/src/debug.js(114,38): error TS2339: Property 'log' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(120,29): error TS2339: Property 'useColors' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(125,37): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(126,13): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(153,11): error TS2339: Property 'save' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(155,3): error TS2323: Cannot redeclare exported variable 'names'. -node_modules/debug/src/debug.js(156,3): error TS2323: Cannot redeclare exported variable 'skips'. -node_modules/debug/src/debug.js(217,12): error TS2304: Cannot find name 'Mixed'. -node_modules/debug/src/debug.js(218,13): error TS2304: Cannot find name 'Mixed'. -node_modules/debug/src/index.js(6,47): error TS2339: Property 'type' does not exist on type 'Process'. -node_modules/debug/src/node.js(26,1): error TS2323: Cannot redeclare exported variable 'colors'. -node_modules/debug/src/node.js(31,5): error TS2323: Cannot redeclare exported variable 'colors'. -node_modules/debug/src/node.js(60,39): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. +node_modules/debug/dist/debug.js(3,100): error TS2539: Cannot assign to '_typeof' because it is not a variable. +node_modules/debug/dist/debug.js(3,165): error TS2539: Cannot assign to '_typeof' because it is not a variable. +node_modules/debug/dist/debug.js(8,21): error TS2304: Cannot find name 'define'. +node_modules/debug/dist/debug.js(8,46): error TS2304: Cannot find name 'define'. +node_modules/debug/dist/debug.js(9,5): error TS2304: Cannot find name 'define'. +node_modules/debug/dist/debug.js(33,33): error TS2554: Expected 1 arguments, but got 2. +node_modules/debug/dist/debug.js(34,27): error TS2554: Expected 1 arguments, but got 2. +node_modules/debug/dist/debug.js(36,21): error TS2339: Property 'code' does not exist on type 'Error'. +node_modules/debug/dist/debug.js(89,38): error TS2339: Property 'length' does not exist on type 'string | number'. + Property 'length' does not exist on type 'number'. +node_modules/debug/dist/debug.js(90,24): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. +node_modules/debug/dist/debug.js(91,47): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(92,41): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(92,57): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(110,11): error TS2322: Type 'undefined' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(116,11): error TS2322: Type 'undefined' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(169,13): error TS2322: Type 'undefined' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(501,30): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(501,66): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(530,18): error TS2339: Property 'diff' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/dist/debug.js(531,18): error TS2339: Property 'prev' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/dist/debug.js(532,18): error TS2339: Property 'curr' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/dist/debug.js(563,25): error TS2551: Property 'formatArgs' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. Did you mean 'formatters'? +node_modules/debug/dist/debug.js(564,30): error TS2339: Property 'log' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/dist/debug.js(564,49): error TS2339: Property 'log' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(570,41): error TS2339: Property 'useColors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(577,34): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(578,25): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(609,23): error TS2339: Property 'save' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(680,19): error TS2304: Cannot find name 'Mixed'. +node_modules/debug/dist/debug.js(681,20): error TS2304: Cannot find name 'Mixed'. +node_modules/debug/dist/debug.js(694,40): error TS2339: Property 'load' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(733,55): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/dist/debug.js(733,74): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/dist/debug.js(733,112): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/dist/debug.js(744,146): error TS2551: Property 'WebkitAppearance' does not exist on type 'CSSStyleDeclaration'. Did you mean 'webkitAppearance'? +node_modules/debug/dist/debug.js(745,78): error TS2339: Property 'firebug' does not exist on type 'Console'. +node_modules/debug/dist/debug.js(799,156): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, ...any[]]'. + Property 'pop' is missing in type 'IArguments'. +node_modules/debug/dist/debug.js(851,21): error TS2304: Cannot find name 'LocalStorage'. +node_modules/debug/src/browser.js(3,100): error TS2539: Cannot assign to '_typeof' because it is not a variable. +node_modules/debug/src/browser.js(3,165): error TS2539: Cannot assign to '_typeof' because it is not a variable. +node_modules/debug/src/browser.js(34,47): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/src/browser.js(34,66): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/src/browser.js(34,104): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/src/browser.js(45,138): error TS2551: Property 'WebkitAppearance' does not exist on type 'CSSStyleDeclaration'. Did you mean 'webkitAppearance'? +node_modules/debug/src/browser.js(46,70): error TS2339: Property 'firebug' does not exist on type 'Console'. +node_modules/debug/src/browser.js(100,148): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, ...any[]]'. +node_modules/debug/src/browser.js(152,13): error TS2304: Cannot find name 'LocalStorage'. +node_modules/debug/src/common.js(51,24): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(51,60): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(80,12): error TS2339: Property 'diff' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/src/common.js(81,12): error TS2339: Property 'prev' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/src/common.js(82,12): error TS2339: Property 'curr' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/src/common.js(113,19): error TS2551: Property 'formatArgs' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. Did you mean 'formatters'? +node_modules/debug/src/common.js(114,24): error TS2339: Property 'log' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/src/common.js(114,43): error TS2339: Property 'log' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(120,35): error TS2339: Property 'useColors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(127,28): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(128,19): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(159,17): error TS2339: Property 'save' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(230,13): error TS2304: Cannot find name 'Mixed'. +node_modules/debug/src/common.js(231,14): error TS2304: Cannot find name 'Mixed'. +node_modules/debug/src/common.js(244,34): error TS2339: Property 'load' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/index.js(7,47): error TS2339: Property 'type' does not exist on type 'Process'. +node_modules/debug/src/index.js(7,78): error TS2339: Property 'browser' does not exist on type 'Process'. +node_modules/debug/src/index.js(7,106): error TS2339: Property '__nwjs' does not exist on type 'Process'. +node_modules/debug/src/node.js(24,1): error TS2323: Cannot redeclare exported variable 'colors'. +node_modules/debug/src/node.js(32,5): error TS2323: Cannot redeclare exported variable 'colors'. +node_modules/debug/src/node.js(53,39): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. -node_modules/debug/src/node.js(60,45): error TS2322: Type 'true' is not assignable to type 'string | undefined'. -node_modules/debug/src/node.js(61,46): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. +node_modules/debug/src/node.js(54,5): error TS2322: Type 'true' is not assignable to type 'string | undefined'. +node_modules/debug/src/node.js(55,48): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. -node_modules/debug/src/node.js(61,52): error TS2322: Type 'false' is not assignable to type 'string | undefined'. -node_modules/debug/src/node.js(62,28): error TS2322: Type 'null' is not assignable to type 'string | undefined'. -node_modules/debug/src/node.js(63,8): error TS2322: Type 'number' is not assignable to type 'string | undefined'. -node_modules/debug/src/node.js(75,35): error TS2339: Property 'colors' does not exist on type 'never'. -node_modules/debug/src/node.js(76,33): error TS2339: Property 'fd' does not exist on type 'WriteStream'. -node_modules/debug/src/node.js(123,27): error TS2339: Property 'hideDate' does not exist on type '{}'. -node_modules/debug/src/node.js(163,3): error TS2322: Type 'string | undefined' is not assignable to type 'string'. +node_modules/debug/src/node.js(56,5): error TS2322: Type 'false' is not assignable to type 'string | undefined'. +node_modules/debug/src/node.js(58,5): error TS2322: Type 'null' is not assignable to type 'string | undefined'. +node_modules/debug/src/node.js(60,5): error TS2322: Type 'number' is not assignable to type 'string | undefined'. +node_modules/debug/src/node.js(71,108): error TS2339: Property 'fd' does not exist on type 'WriteStream'. +node_modules/debug/src/node.js(108,55): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any, ...any[]]'. + Property '0' is missing in type 'IArguments'. +node_modules/debug/src/node.js(136,3): error TS2322: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. diff --git a/tests/baselines/reference/user/enhanced-resolve.log b/tests/baselines/reference/user/enhanced-resolve.log index 24d0c3b9839..7dd284bf166 100644 --- a/tests/baselines/reference/user/enhanced-resolve.log +++ b/tests/baselines/reference/user/enhanced-resolve.log @@ -1,10 +1,10 @@ Exit Code: 1 Standard output: -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(116,18): error TS2345: Argument of type 'Timer | null' is not assignable to parameter of type 'number | undefined'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(116,18): error TS2345: Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'. Type 'null' is not assignable to type 'number | undefined'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(129,18): error TS2345: Argument of type 'Timer | null' is not assignable to parameter of type 'number | undefined'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(129,18): error TS2345: Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'. Type 'null' is not assignable to type 'number | undefined'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(147,18): error TS2345: Argument of type 'Timer | null' is not assignable to parameter of type 'number | undefined'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(147,18): error TS2345: Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'. Type 'null' is not assignable to type 'number | undefined'. node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(176,19): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(179,23): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. diff --git a/tests/baselines/reference/user/formik.log b/tests/baselines/reference/user/formik.log deleted file mode 100644 index 7daf2b6efee..00000000000 --- a/tests/baselines/reference/user/formik.log +++ /dev/null @@ -1,17 +0,0 @@ -Exit Code: 1 -Standard output: -index.tsx(30,17): error TS7006: Parameter 'values' implicitly has an 'any' type. -index.tsx(43,9): error TS7006: Parameter 'values' implicitly has an 'any' type. -index.tsx(44,11): error TS7031: Binding element 'setSubmitting' implicitly has an 'any' type. -index.tsx(44,26): error TS7031: Binding element 'setErrors' implicitly has an 'any' type. -index.tsx(60,9): error TS7031: Binding element 'values' implicitly has an 'any' type. -index.tsx(61,9): error TS7031: Binding element 'errors' implicitly has an 'any' type. -index.tsx(62,9): error TS7031: Binding element 'touched' implicitly has an 'any' type. -index.tsx(63,9): error TS7031: Binding element 'handleChange' implicitly has an 'any' type. -index.tsx(64,9): error TS7031: Binding element 'handleBlur' implicitly has an 'any' type. -index.tsx(65,9): error TS7031: Binding element 'handleSubmit' implicitly has an 'any' type. -index.tsx(66,9): error TS7031: Binding element 'isSubmitting' implicitly has an 'any' type. - - - -Standard error: diff --git a/tests/baselines/reference/user/graceful-fs.log b/tests/baselines/reference/user/graceful-fs.log index ac14b051d15..ef5a4e24f37 100644 --- a/tests/baselines/reference/user/graceful-fs.log +++ b/tests/baselines/reference/user/graceful-fs.log @@ -5,21 +5,20 @@ node_modules/graceful-fs/fs.js(17,38): error TS2345: Argument of type 'PropertyD Type 'undefined' is not assignable to type 'PropertyDescriptor & ThisType'. Type 'undefined' is not assignable to type 'PropertyDescriptor'. node_modules/graceful-fs/graceful-fs.js(12,3): error TS2322: Type '(msg: string, ...param: any[]) => void' is not assignable to type '() => void'. +node_modules/graceful-fs/graceful-fs.js(15,37): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any, ...any[]]'. + Property '0' is missing in type 'IArguments'. node_modules/graceful-fs/graceful-fs.js(22,5): error TS2554: Expected 0 arguments, but got 1. -node_modules/graceful-fs/graceful-fs.js(37,1): error TS2322: Type '(fd: any, cb: any) => any' is not assignable to type 'typeof close'. - Property '__promisify__' is missing in type '(fd: any, cb: any) => any'. +node_modules/graceful-fs/graceful-fs.js(37,1): error TS2322: Type '(fd: any, cb: any) => void' is not assignable to type 'typeof close'. + Property '__promisify__' is missing in type '(fd: any, cb: any) => void'. +node_modules/graceful-fs/graceful-fs.js(51,37): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[number]'. + Property '0' is missing in type 'IArguments'. node_modules/graceful-fs/graceful-fs.js(161,5): error TS2539: Cannot assign to 'ReadStream' because it is not a variable. node_modules/graceful-fs/graceful-fs.js(162,5): error TS2539: Cannot assign to 'WriteStream' because it is not a variable. +node_modules/graceful-fs/graceful-fs.js(180,68): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, ...any[]]'. + Property 'pop' is missing in type 'IArguments'. +node_modules/graceful-fs/graceful-fs.js(203,70): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, ...any[]]'. node_modules/graceful-fs/graceful-fs.js(252,3): error TS2554: Expected 0 arguments, but got 3. node_modules/graceful-fs/graceful-fs.js(259,5): error TS2554: Expected 0 arguments, but got 3. -node_modules/graceful-fs/polyfills.js(7,24): error TS2339: Property 'env' does not exist on type 'typeof process'. -node_modules/graceful-fs/polyfills.js(7,60): error TS2339: Property 'platform' does not exist on type 'typeof process'. -node_modules/graceful-fs/polyfills.js(32,15): error TS2339: Property 'version' does not exist on type 'typeof process'. -node_modules/graceful-fs/polyfills.js(73,23): error TS2339: Property 'nextTick' does not exist on type 'typeof process'. -node_modules/graceful-fs/polyfills.js(79,23): error TS2339: Property 'nextTick' does not exist on type 'typeof process'. -node_modules/graceful-fs/polyfills.js(229,62): error TS2339: Property 'nextTick' does not exist on type 'typeof process'. -node_modules/graceful-fs/polyfills.js(323,26): error TS2339: Property 'getuid' does not exist on type 'typeof process'. -node_modules/graceful-fs/polyfills.js(323,44): error TS2339: Property 'getuid' does not exist on type 'typeof process'. diff --git a/tests/baselines/reference/user/jimp.log b/tests/baselines/reference/user/jimp.log deleted file mode 100644 index 2a11d85e4c5..00000000000 --- a/tests/baselines/reference/user/jimp.log +++ /dev/null @@ -1,9 +0,0 @@ -Exit Code: 1 -Standard output: -node_modules/jimp/jimp.d.ts(487,12): error TS7010: 'appendConstructorOption', which lacks return-type annotation, implicitly has an 'any' return type. -node_modules/jimp/jimp.d.ts(529,12): error TS7010: 'measureText', which lacks return-type annotation, implicitly has an 'any' return type. -node_modules/jimp/jimp.d.ts(530,12): error TS7010: 'measureTextHeight', which lacks return-type annotation, implicitly has an 'any' return type. - - - -Standard error: diff --git a/tests/baselines/reference/user/lodash.log b/tests/baselines/reference/user/lodash.log index 6fd61c0fb69..0418c19fe2c 100644 --- a/tests/baselines/reference/user/lodash.log +++ b/tests/baselines/reference/user/lodash.log @@ -36,11 +36,14 @@ node_modules/lodash/_baseDifference.js(37,5): error TS2322: Type '(array?: any[] node_modules/lodash/_baseDifference.js(43,5): error TS2322: Type 'SetCache' is not assignable to type 'any[]'. Property 'length' is missing in type 'SetCache'. node_modules/lodash/_baseDifference.js(60,15): error TS2554: Expected 2 arguments, but got 3. -node_modules/lodash/_baseFlatten.js(19,17): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. +node_modules/lodash/_baseFlatten.js(19,29): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. node_modules/lodash/_baseFlatten.js(24,22): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures. node_modules/lodash/_baseFlatten.js(24,22): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_baseFlatten.js(24,22): error TS2722: Cannot invoke an object which is possibly 'undefined'. +node_modules/lodash/_baseHas.js(16,56): error TS2345: Argument of type 'string | any[]' is not assignable to parameter of type 'string | number | symbol'. + Type 'any[]' is not assignable to type 'string | number | symbol'. + Type 'any[]' is not assignable to type 'symbol'. node_modules/lodash/_baseIntersection.js(53,40): error TS2345: Argument of type 'Function | undefined' is not assignable to parameter of type 'Function'. Type 'undefined' is not assignable to type 'Function'. node_modules/lodash/_baseIntersection.js(60,54): error TS2345: Argument of type 'Function | undefined' is not assignable to parameter of type 'Function'. @@ -73,9 +76,11 @@ node_modules/lodash/_baseUniq.js(30,5): error TS2322: Type '(array?: any[] | und node_modules/lodash/_baseUniq.js(33,33): error TS2554: Expected 0 arguments, but got 1. node_modules/lodash/_baseUniq.js(39,5): error TS2322: Type 'SetCache' is not assignable to type 'any[]'. node_modules/lodash/_baseUniq.js(62,15): error TS2554: Expected 2 arguments, but got 3. +node_modules/lodash/_baseWrapperValue.js(18,21): error TS2339: Property 'value' does not exist on type 'LazyWrapper'. node_modules/lodash/_cloneArrayBuffer.js(11,16): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. node_modules/lodash/_cloneBuffer.js(4,69): error TS2339: Property 'nodeType' does not exist on type '(buffer: any, isDeep?: boolean | undefined) => any'. node_modules/lodash/_cloneBuffer.js(7,80): error TS2339: Property 'nodeType' does not exist on type '{ "../../../tests/cases/user/lodash/node_modules/lodash/_cloneBuffer": (buffer: any, isDeep?: boolean | undefined) => any; }'. +node_modules/lodash/_cloneBuffer.js(20,12): error TS2587: JSDoc type 'Buffer' circularly references itself. node_modules/lodash/_cloneBuffer.js(22,14): error TS2577: Return type annotation circularly references itself. node_modules/lodash/_cloneBuffer.js(24,22): error TS2502: 'buffer' is referenced directly or indirectly in its own type annotation. node_modules/lodash/_copySymbols.js(13,29): error TS2554: Expected 0 arguments, but got 1. @@ -126,6 +131,8 @@ node_modules/lodash/_createWrap.js(96,26): error TS2345: Argument of type 'Timer node_modules/lodash/_createWrap.js(97,100): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_createWrap.js(98,28): error TS2345: Argument of type 'TimerHandler' is not assignable to parameter of type 'Function'. Type 'string' is not assignable to type 'Function'. +node_modules/lodash/_createWrap.js(100,44): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[TimerHandler, number, any?, (any[] | undefined)?, (any[] | undefined)?, (any[] | undefined)?, (any[] | undefined)?, (any[] | undefined)?, (number | undefined)?, (number | undefined)?]'. + Property '0' is missing in type 'any[]'. node_modules/lodash/_createWrap.js(103,51): error TS2345: Argument of type 'TimerHandler' is not assignable to parameter of type 'Function'. Type 'string' is not assignable to type 'Function'. node_modules/lodash/_customDefaultsMerge.js(22,35): error TS2345: Argument of type 'undefined' is not assignable to parameter of type 'number'. @@ -150,7 +157,7 @@ node_modules/lodash/_memoizeCapped.js(22,22): error TS2339: Property 'cache' doe node_modules/lodash/_mergeData.js(60,26): error TS2554: Expected 4 arguments, but got 3. node_modules/lodash/_mergeData.js(67,26): error TS2554: Expected 4 arguments, but got 3. node_modules/lodash/_nodeUtil.js(7,80): error TS2339: Property 'nodeType' does not exist on type '{ "../../../tests/cases/user/lodash/node_modules/lodash/_nodeUtil": any; }'. -node_modules/lodash/_nodeUtil.js(13,47): error TS2339: Property 'process' does not exist on type 'boolean | Global'. +node_modules/lodash/_nodeUtil.js(13,47): error TS2339: Property 'process' does not exist on type 'false | Global'. Property 'process' does not exist on type 'false'. node_modules/lodash/_overRest.js(20,42): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_overRest.js(24,27): error TS2532: Object is possibly 'undefined'. @@ -158,8 +165,11 @@ node_modules/lodash/_overRest.js(27,27): error TS2532: Object is possibly 'undef node_modules/lodash/_overRest.js(28,22): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_overRest.js(31,15): error TS2538: Type 'undefined' cannot be used as an index type. node_modules/lodash/_root.js(4,56): error TS2339: Property 'Object' does not exist on type 'Window'. +node_modules/lodash/_stackSet.js(21,22): error TS2339: Property '__data__' does not exist on type 'ListCache'. +node_modules/lodash/_stackSet.js(24,26): error TS2339: Property 'size' does not exist on type 'ListCache'. node_modules/lodash/_unicodeWords.js(62,20): error TS8024: JSDoc '@param' tag has name 'The', but there is no parameter with that name. node_modules/lodash/_updateWrapDetails.js(34,5): error TS1223: 'returns' tag already specified. +node_modules/lodash/_wrapperClone.js(14,20): error TS2339: Property 'clone' does not exist on type 'LazyWrapper'. node_modules/lodash/ary.js(16,10): error TS1003: Identifier expected. node_modules/lodash/ary.js(16,10): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. node_modules/lodash/before.js(34,7): error TS2322: Type 'undefined' is not assignable to type 'Function'. @@ -180,7 +190,7 @@ node_modules/lodash/cloneWith.js(39,27): error TS2345: Argument of type 'number' node_modules/lodash/conforms.js(32,41): error TS2345: Argument of type 'number' is not assignable to parameter of type 'boolean'. node_modules/lodash/core.js(68,58): error TS2339: Property 'Object' does not exist on type 'Window'. node_modules/lodash/core.js(77,82): error TS2339: Property 'nodeType' does not exist on type 'NodeModule'. -node_modules/lodash/core.js(540,19): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. +node_modules/lodash/core.js(540,31): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. node_modules/lodash/core.js(545,24): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures. node_modules/lodash/core.js(545,24): error TS2532: Object is possibly 'undefined'. @@ -227,6 +237,9 @@ node_modules/lodash/core.js(2183,41): error TS8024: JSDoc '@param' tag has name node_modules/lodash/core.js(2473,21): error TS2554: Expected 0 arguments, but got 1. node_modules/lodash/core.js(2609,39): error TS2554: Expected 0 arguments, but got 1. node_modules/lodash/core.js(2644,12): error TS2554: Expected 3-5 arguments, but got 2. +node_modules/lodash/core.js(3245,58): error TS2345: Argument of type 'string | any[]' is not assignable to parameter of type 'string | number | symbol'. + Type 'any[]' is not assignable to type 'string | number | symbol'. + Type 'any[]' is not assignable to type 'symbol'. node_modules/lodash/core.js(3354,53): error TS2538: Type 'any[]' cannot be used as an index type. node_modules/lodash/core.js(3424,41): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'. Type 'Function' provides no match for the signature '(substring: string, ...args: any[]): string'. @@ -273,42 +286,42 @@ node_modules/lodash/findIndex.js(52,31): error TS2554: Expected 0-1 arguments, b node_modules/lodash/findKey.js(41,30): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/findLastIndex.js(56,31): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/findLastKey.js(41,30): error TS2554: Expected 0-1 arguments, but got 2. -node_modules/lodash/fp/_baseConvert.js(144,5): error TS2559: Type 'Function' has no properties in common with type '{ cap?: boolean; curry?: boolean; fixed?: boolean; immutable?: boolean; rearg?: boolean; }'. -node_modules/lodash/fp/_baseConvert.js(145,5): error TS2322: Type 'string' is not assignable to type 'Function'. -node_modules/lodash/fp/_baseConvert.js(146,5): error TS2322: Type 'undefined' is not assignable to type 'string'. -node_modules/lodash/fp/_baseConvert.js(165,31): error TS2339: Property 'runInContext' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(184,21): error TS2339: Property 'ary' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(143,5): error TS2559: Type 'Function' has no properties in common with type '{ cap?: boolean; curry?: boolean; fixed?: boolean; immutable?: boolean; rearg?: boolean; }'. +node_modules/lodash/fp/_baseConvert.js(144,5): error TS2322: Type 'string' is not assignable to type 'Function'. +node_modules/lodash/fp/_baseConvert.js(145,5): error TS2322: Type 'undefined' is not assignable to type 'string'. +node_modules/lodash/fp/_baseConvert.js(164,31): error TS2339: Property 'runInContext' does not exist on type 'Function'. +node_modules/lodash/fp/_baseConvert.js(183,21): error TS2339: Property 'ary' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'ary' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(185,24): error TS2339: Property 'assign' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(184,24): error TS2339: Property 'assign' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'assign' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(186,23): error TS2339: Property 'clone' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(185,23): error TS2339: Property 'clone' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'clone' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(187,23): error TS2339: Property 'curry' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(186,23): error TS2339: Property 'curry' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'curry' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(188,22): error TS2339: Property 'forEach' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(187,22): error TS2339: Property 'forEach' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'forEach' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(189,25): error TS2339: Property 'isArray' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(188,25): error TS2339: Property 'isArray' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'isArray' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(190,25): error TS2339: Property 'isError' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(189,25): error TS2339: Property 'isError' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'isError' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(191,28): error TS2339: Property 'isFunction' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(190,28): error TS2339: Property 'isFunction' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'isFunction' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(192,27): error TS2339: Property 'isWeakMap' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(191,27): error TS2339: Property 'isWeakMap' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'isWeakMap' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(193,22): error TS2339: Property 'keys' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(192,22): error TS2339: Property 'keys' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'keys' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(194,23): error TS2339: Property 'rearg' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(193,23): error TS2339: Property 'rearg' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'rearg' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(195,27): error TS2339: Property 'toInteger' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(194,27): error TS2339: Property 'toInteger' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'toInteger' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(196,24): error TS2339: Property 'toPath' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. +node_modules/lodash/fp/_baseConvert.js(195,24): error TS2339: Property 'toPath' does not exist on type 'Function | { 'ary': any; 'assign': any; 'clone': any; 'curry': any; 'forEach': any; 'isArray': any; 'isError': any; 'isFunction': any; 'isWeakMap': any; 'iteratee': any; 'keys': any; 'rearg': any; 'toInteger': any; 'toPath': any; }'. Property 'toPath' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(263,57): error TS2345: Argument of type '{ cap?: boolean; curry?: boolean; fixed?: boolean; immutable?: boolean; rearg?: boolean; } | undefined' is not assignable to parameter of type 'Function'. +node_modules/lodash/fp/_baseConvert.js(262,57): error TS2345: Argument of type '{ cap?: boolean; curry?: boolean; fixed?: boolean; immutable?: boolean; rearg?: boolean; } | undefined' is not assignable to parameter of type 'Function'. Type 'undefined' is not assignable to type 'Function'. -node_modules/lodash/fp/_baseConvert.js(379,14): error TS2339: Property 'runInContext' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(516,33): error TS2339: Property 'placeholder' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(559,5): error TS2339: Property 'convert' does not exist on type 'Function'. -node_modules/lodash/fp/_baseConvert.js(561,7): error TS2339: Property 'placeholder' does not exist on type 'Function'. +node_modules/lodash/fp/_baseConvert.js(378,14): error TS2339: Property 'runInContext' does not exist on type 'Function'. +node_modules/lodash/fp/_baseConvert.js(513,31): error TS2339: Property 'placeholder' does not exist on type 'Function'. +node_modules/lodash/fp/_baseConvert.js(556,5): error TS2339: Property 'convert' does not exist on type 'Function'. +node_modules/lodash/fp/_baseConvert.js(557,5): error TS2339: Property 'placeholder' does not exist on type 'Function'. node_modules/lodash/fp/_convertBrowser.js(12,30): error TS2345: Argument of type 'Function' is not assignable to parameter of type 'string'. node_modules/lodash/fp/_convertBrowser.js(15,12): error TS2304: Cannot find name '_'. node_modules/lodash/fp/_convertBrowser.js(15,38): error TS2304: Cannot find name '_'. @@ -360,6 +373,7 @@ node_modules/lodash/parseInt.js(24,10): error TS8024: JSDoc '@param' tag has nam node_modules/lodash/partial.js(48,9): error TS2339: Property 'placeholder' does not exist on type 'Function'. node_modules/lodash/partialRight.js(47,14): error TS2339: Property 'placeholder' does not exist on type 'Function'. node_modules/lodash/pickBy.js(33,12): error TS2722: Cannot invoke an object which is possibly 'undefined'. +node_modules/lodash/plant.js(42,21): error TS2339: Property '__wrapped__' does not exist on type '{}'. node_modules/lodash/property.js(29,37): error TS2345: Argument of type 'string | symbol' is not assignable to parameter of type 'string'. Type 'symbol' is not assignable to type 'string'. node_modules/lodash/pullAllBy.js(29,34): error TS2554: Expected 0-1 arguments, but got 2. @@ -435,7 +449,9 @@ node_modules/lodash/unionWith.js(31,42): error TS2345: Argument of type '(value: node_modules/lodash/uniqBy.js(28,52): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/words.js(15,10): error TS1003: Identifier expected. node_modules/lodash/words.js(15,10): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. +node_modules/lodash/wrapperAt.js(34,17): error TS2339: Property 'slice' does not exist on type 'LazyWrapper'. node_modules/lodash/wrapperAt.js(40,51): error TS2339: Property 'thru' does not exist on type 'LodashWrapper'. +node_modules/lodash/wrapperReverse.js(33,23): error TS2339: Property 'reverse' does not exist on type 'LazyWrapper'. node_modules/lodash/xorBy.js(36,58): error TS2554: Expected 0-1 arguments, but got 2. diff --git a/tests/baselines/reference/user/npm.log b/tests/baselines/reference/user/npm.log index f2db4a09546..435d962fa95 100644 --- a/tests/baselines/reference/user/npm.log +++ b/tests/baselines/reference/user/npm.log @@ -29,6 +29,8 @@ node_modules/npm/bin/npm-cli.js(128,13): error TS2339: Property 'command' does n node_modules/npm/bin/npm-cli.js(132,17): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/bin/npm-cli.js(134,17): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/bin/npm-cli.js(136,17): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. +node_modules/npm/bin/npm-cli.js(140,32): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?]'. + Property 'pop' is missing in type 'IArguments'. node_modules/npm/html/static/toc.js(3,40): error TS2531: Object is possibly 'null'. node_modules/npm/lib/access.js(58,46): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/access.js(65,18): error TS2339: Property 'registry' does not exist on type 'typeof EventEmitter'. @@ -58,7 +60,10 @@ node_modules/npm/lib/auth/legacy.js(12,30): error TS2339: Property 'config' does node_modules/npm/lib/auth/legacy.js(35,16): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/auth/legacy.js(69,33): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/auth/oauth.js(5,7): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. +node_modules/npm/lib/auth/oauth.js(6,29): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, any?, any?]'. + Property 'pop' is missing in type 'IArguments'. node_modules/npm/lib/auth/saml.js(5,7): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. +node_modules/npm/lib/auth/saml.js(6,29): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, any?, any?]'. node_modules/npm/lib/auth/sso.js(7,21): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/auth/sso.js(20,7): error TS2339: Property 'registry' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/auth/sso.js(28,36): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. @@ -136,6 +141,7 @@ node_modules/npm/lib/config/core.js(160,23): error TS2339: Property 'get' does n node_modules/npm/lib/config/core.js(165,10): error TS2339: Property 'once' does not exist on type 'Conf'. node_modules/npm/lib/config/core.js(176,23): error TS2339: Property 'get' does not exist on type 'Conf'. node_modules/npm/lib/config/core.js(190,5): error TS2323: Cannot redeclare exported variable 'loaded'. +node_modules/npm/lib/config/core.js(208,24): error TS2339: Property 'list' does not exist on type 'Conf'. node_modules/npm/lib/config/core.js(213,28): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. node_modules/npm/lib/config/core.js(237,21): error TS2339: Property 'sources' does not exist on type 'Conf'. node_modules/npm/lib/config/core.js(245,17): error TS2339: Property 'emit' does not exist on type 'Conf'. @@ -147,6 +153,8 @@ node_modules/npm/lib/config/core.js(333,10): error TS2339: Property 'emit' does node_modules/npm/lib/config/core.js(409,29): error TS2345: Argument of type '(orig: string, esc: any, name: any) => string | undefined' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. +node_modules/npm/lib/config/defaults.js(20,52): error TS2345: Argument of type 'never[]' is not assignable to parameter of type '[any, ...any[]]'. + Property '0' is missing in type 'never[]'. node_modules/npm/lib/config/gentle-fs.js(16,11): error TS2339: Property 'prefix' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config/gentle-fs.js(17,11): error TS2339: Property 'globalPrefix' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config/gentle-fs.js(18,11): error TS2339: Property 'dir' does not exist on type 'typeof EventEmitter'. @@ -324,7 +332,8 @@ node_modules/npm/lib/help.js(186,11): error TS2339: Property 'argv' does not exi node_modules/npm/lib/help.js(187,20): error TS2339: Property 'argv' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/help.js(196,26): error TS2339: Property 'commands' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/help.js(197,22): error TS2339: Property 'deref' does not exist on type 'typeof EventEmitter'. -node_modules/npm/lib/help.js(199,14): error TS2345: Argument of type 'any[]' is not assignable to parameter of type 'never'. +node_modules/npm/lib/help.js(199,15): error TS2322: Type 'string' is not assignable to type 'never'. +node_modules/npm/lib/help.js(199,18): error TS2322: Type 'any' is not assignable to type 'never'. node_modules/npm/lib/help.js(199,22): error TS2339: Property 'commands' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/help.js(206,33): error TS2339: Property 'length' does not exist on type 'never'. node_modules/npm/lib/help.js(207,14): error TS2339: Property 'split' does not exist on type 'never'. @@ -429,8 +438,8 @@ node_modules/npm/lib/install.js(268,26): error TS2339: Property 'config' does no node_modules/npm/lib/install.js(269,9): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/install.js(272,11): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/install.js(273,7): error TS2532: Object is possibly 'undefined'. -node_modules/npm/lib/install.js(273,7): error TS2684: The 'this' context of type '((err: any, ...args: any[]) => any) | undefined' is not assignable to method's 'this' of type 'Function'. - Type 'undefined' is not assignable to type 'Function'. +node_modules/npm/lib/install.js(273,7): error TS2684: The 'this' context of type '((err: any, ...args: any[]) => any) | undefined' is not assignable to method's 'this' of type '(this: null, err?: any, ...args: any[]) => any'. + Type 'undefined' is not assignable to type '(this: null, err?: any, ...args: any[]) => any'. node_modules/npm/lib/install.js(340,25): error TS2339: Property 'failing' does not exist on type 'Installer'. node_modules/npm/lib/install.js(369,18): error TS2345: Argument of type '"time"' is not assignable to parameter of type 'Signals'. node_modules/npm/lib/install.js(376,16): error TS2345: Argument of type '"timeEnd"' is not assignable to parameter of type 'Signals'. @@ -676,11 +685,9 @@ node_modules/npm/lib/run-script.js(35,22): error TS2339: Property 'localPrefix' node_modules/npm/lib/run-script.js(46,26): error TS2339: Property 'localPrefix' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/run-script.js(56,20): error TS2339: Property 'localPrefix' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/run-script.js(66,28): error TS2339: Property 'localPrefix' does not exist on type 'typeof EventEmitter'. -node_modules/npm/lib/run-script.js(77,21): error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'ConcatArray'. - Types of property 'slice' are incompatible. - Type '(start?: number | undefined, end?: number | undefined) => string[]' is not assignable to type '(start?: number | undefined, end?: number | undefined) => never[]'. - Type 'string[]' is not assignable to type 'never[]'. - Type 'string' is not assignable to type 'never'. +node_modules/npm/lib/run-script.js(77,22): error TS2322: Type 'string' is not assignable to type 'never'. +node_modules/npm/lib/run-script.js(77,33): error TS2322: Type 'string' is not assignable to type 'never'. +node_modules/npm/lib/run-script.js(77,36): error TS2322: Type 'string' is not assignable to type 'never'. node_modules/npm/lib/run-script.js(94,13): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/run-script.js(99,13): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/run-script.js(148,22): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. @@ -838,6 +845,8 @@ node_modules/npm/lib/utils/metrics.js(61,31): error TS2345: Argument of type 'Bu node_modules/npm/lib/utils/metrics.js(62,7): error TS2339: Property 'load' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/utils/metrics.js(64,9): error TS2339: Property 'registry' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/utils/metrics.js(65,9): error TS2339: Property 'registry' does not exist on type 'typeof EventEmitter'. +node_modules/npm/lib/utils/output.js(6,30): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, ...any[]]'. + Property 'pop' is missing in type 'IArguments'. node_modules/npm/lib/utils/perf.js(9,12): error TS2345: Argument of type '"time"' is not assignable to parameter of type 'Signals'. node_modules/npm/lib/utils/perf.js(10,12): error TS2345: Argument of type '"timeEnd"' is not assignable to parameter of type 'Signals'. node_modules/npm/lib/utils/read-local-package.js(7,11): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. @@ -910,6 +919,10 @@ node_modules/npm/test/broken-under-nyc-and-travis/whoami.js(7,20): error TS2307: node_modules/npm/test/common-tap.js(5,47): error TS2339: Property '_extend' does not exist on type 'typeof import("util")'. node_modules/npm/test/common-tap.js(10,3): error TS2322: Type '(...args: any[]) => void' is not assignable to type 'typeof setImmediate'. Property '__promisify__' is missing in type '(...args: any[]) => void'. +node_modules/npm/test/common-tap.js(10,36): error TS2322: Type '(...args: any[]) => void' is not assignable to type '(callback: (...args: any[]) => void, ...args: any[]) => Immediate'. + Type 'void' is not assignable to type 'Immediate'. +node_modules/npm/test/common-tap.js(12,28): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[(...args: any[]) => void, number, ...any[]]'. + Property '0' is missing in type 'any[]'. node_modules/npm/test/common-tap.js(175,17): error TS2339: Property '_storage' does not exist on type 'Environment'. node_modules/npm/test/common-tap.js(181,31): error TS2339: Property '_storage' does not exist on type 'Environment'. node_modules/npm/test/common-tap.js(192,12): error TS2339: Property '_storage' does not exist on type 'Environment'. @@ -928,6 +941,8 @@ node_modules/npm/test/need-npm5-update/legacy-dir-bin.js(2,20): error TS2307: Ca node_modules/npm/test/need-npm5-update/legacy-dir-bin.js(11,21): error TS2307: Cannot find module 'tacks'. node_modules/npm/test/need-npm5-update/legacy-npm-self-install.js(2,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/need-npm5-update/legacy-npm-self-install.js(12,47): error TS2339: Property '_extend' does not exist on type 'typeof import("util")'. +node_modules/npm/test/need-npm5-update/legacy-npm-self-install.js(34,42): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'string[]'. + Property 'pop' is missing in type 'IArguments'. node_modules/npm/test/need-npm5-update/legacy-npm-self-install.js(48,3): error TS2322: Type 'null' is not assignable to type 'string | undefined'. node_modules/npm/test/need-npm5-update/legacy-npm-self-install.js(49,3): error TS2322: Type 'null' is not assignable to type 'string | undefined'. node_modules/npm/test/need-npm5-update/legacy-optional-deps.js(4,20): error TS2307: Cannot find module 'tap'. @@ -937,6 +952,7 @@ node_modules/npm/test/need-npm5-update/legacy-shrinkwrap.js(2,20): error TS2307: node_modules/npm/test/need-npm5-update/legacy-shrinkwrap.js(6,21): error TS2307: Cannot find module 'tacks'. node_modules/npm/test/need-npm5-update/lifecycle-signal.js(8,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/need-npm5-update/move-no-clobber-dest-node-modules.js(3,20): error TS2307: Cannot find module 'tap'. +node_modules/npm/test/need-npm5-update/move-no-clobber-dest-node-modules.js(11,48): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'string[]'. node_modules/npm/test/need-npm5-update/need-only-update-save-optional/update-save.js(5,18): error TS2307: Cannot find module 'npm-registry-mock'. node_modules/npm/test/need-npm5-update/need-only-update-save-optional/update-save.js(8,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/need-npm5-update/need-only-update-save-optional/update-save.js(10,22): error TS2307: Cannot find module '../common-tap.js'. @@ -945,13 +961,7 @@ node_modules/npm/test/need-npm5-update/need-outdated/update-symlink.js(6,20): er node_modules/npm/test/need-npm5-update/need-outdated/update-symlink.js(8,22): error TS2307: Cannot find module '../common-tap.js'. node_modules/npm/test/need-npm5-update/outdated-depth-deep.js(3,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/need-npm5-update/outdated-depth-deep.js(5,18): error TS2307: Cannot find module 'npm-registry-mock'. -node_modules/npm/test/need-npm5-update/outdated-depth-deep.js(69,28): error TS2345: Argument of type '(string | number)[]' is not assignable to parameter of type 'string | ConcatArray'. - Type '(string | number)[]' is not assignable to type 'ConcatArray'. - Types of property 'slice' are incompatible. - Type '(start?: number | undefined, end?: number | undefined) => (string | number)[]' is not assignable to type '(start?: number | undefined, end?: number | undefined) => string[]'. - Type '(string | number)[]' is not assignable to type 'string[]'. - Type 'string | number' is not assignable to type 'string'. - Type 'number' is not assignable to type 'string'. +node_modules/npm/test/need-npm5-update/outdated-depth-deep.js(69,52): error TS2322: Type 'number' is not assignable to type 'string'. node_modules/npm/test/need-npm5-update/outdated-depth-integer.js(2,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/need-npm5-update/outdated-depth-integer.js(5,18): error TS2307: Cannot find module 'npm-registry-mock'. node_modules/npm/test/need-npm5-update/outdated-depth-integer.js(55,9): error TS2339: Property 'load' does not exist on type 'typeof EventEmitter'. @@ -1443,6 +1453,8 @@ node_modules/npm/test/tap/outdated-json.js(5,18): error TS2307: Cannot find modu node_modules/npm/test/tap/outdated-json.js(8,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/outdated-long.js(5,18): error TS2307: Cannot find module 'npm-registry-mock'. node_modules/npm/test/tap/outdated-long.js(7,20): error TS2307: Cannot find module 'tap'. +node_modules/npm/test/tap/outdated-long.js(63,31): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. + Property 'pop' is missing in type 'IArguments'. node_modules/npm/test/tap/outdated-long.js(66,9): error TS2339: Property 'load' does not exist on type 'typeof EventEmitter'. node_modules/npm/test/tap/outdated-long.js(74,13): error TS2339: Property 'install' does not exist on type 'typeof EventEmitter'. node_modules/npm/test/tap/outdated-long.js(76,15): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. @@ -1451,6 +1463,7 @@ node_modules/npm/test/tap/outdated.js(5,18): error TS2307: Cannot find module 'n node_modules/npm/test/tap/outdated.js(7,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/outdated.js(92,9): error TS2339: Property 'load' does not exist on type 'typeof EventEmitter'. node_modules/npm/test/tap/outdated.js(100,13): error TS2339: Property 'install' does not exist on type 'typeof EventEmitter'. +node_modules/npm/test/tap/outdated.js(103,39): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. node_modules/npm/test/tap/outdated.js(105,15): error TS2339: Property 'outdated' does not exist on type 'typeof EventEmitter'. node_modules/npm/test/tap/override-bundled.js(3,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/owner.js(1,18): error TS2307: Cannot find module 'npm-registry-mock'. @@ -1492,7 +1505,6 @@ node_modules/npm/test/tap/process-logger.js(9,37): error TS2345: Argument of typ node_modules/npm/test/tap/process-logger.js(10,37): error TS2345: Argument of type '"log"' is not assignable to parameter of type 'Signals'. node_modules/npm/test/tap/progress-config.js(3,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/progress-config.js(12,29): error TS2307: Cannot find module 'require-inject'. -node_modules/npm/test/tap/progress-config.js(18,9): error TS2339: Property 'stderr' does not exist on type 'typeof process'. node_modules/npm/test/tap/prune-dev-dep-cycle.js(4,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/prune-dev-dep-cycle.js(5,21): error TS2307: Cannot find module 'tacks'. node_modules/npm/test/tap/prune-dev-dep-with-bins.js(4,20): error TS2307: Cannot find module 'tap'. diff --git a/tests/baselines/reference/user/npmlog.log b/tests/baselines/reference/user/npmlog.log index cdd163fa0f1..c9662cd1551 100644 --- a/tests/baselines/reference/user/npmlog.log +++ b/tests/baselines/reference/user/npmlog.log @@ -4,6 +4,8 @@ node_modules/npmlog/log.js(83,12): error TS2551: Property '_pause' does not exis node_modules/npmlog/log.js(149,8): error TS2551: Property '_paused' does not exist on type 'typeof EventEmitter'. Did you mean 'pause'? node_modules/npmlog/log.js(154,13): error TS2551: Property '_paused' does not exist on type 'typeof EventEmitter'. Did you mean 'pause'? node_modules/npmlog/log.js(155,8): error TS2551: Property '_paused' does not exist on type 'typeof EventEmitter'. Did you mean 'pause'? +node_modules/npmlog/log.js(194,37): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[any, ...any[]]'. + Property '0' is missing in type 'any[]'. node_modules/npmlog/log.js(218,12): error TS2551: Property '_paused' does not exist on type 'typeof EventEmitter'. Did you mean 'pause'? node_modules/npmlog/log.js(271,16): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. diff --git a/tests/baselines/reference/user/prettier.log b/tests/baselines/reference/user/prettier.log index 0fd19e0d9a7..ae8f5cee3f1 100644 --- a/tests/baselines/reference/user/prettier.log +++ b/tests/baselines/reference/user/prettier.log @@ -6,6 +6,9 @@ src/cli/util.js(262,64): error TS2339: Property 'length' does not exist on type src/cli/util.js(335,52): error TS2339: Property 'length' does not exist on type 'Ignore'. src/cli/util.js(396,46): error TS2345: Argument of type 'null' is not assignable to parameter of type 'number | undefined'. src/cli/util.js(403,39): error TS2339: Property 'grey' does not exist on type 'typeof import("../../../node_modules/chalk/types/index")'. +src/cli/util.js(454,16): error TS2339: Property 'type' does not exist on type 'never'. +src/cli/util.js(455,16): error TS2339: Property 'oppositeDescription' does not exist on type 'never'. +src/cli/util.js(456,17): error TS2339: Property 'name' does not exist on type 'never'. src/common/parser-create-error.js(8,9): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. src/config/resolve-config.js(75,32): error TS2345: Argument of type '{ sync: false; }' is not assignable to parameter of type '{ cache: boolean; sync: boolean; }'. Property 'cache' is missing in type '{ sync: false; }'. @@ -14,6 +17,8 @@ src/config/resolve-config.js(82,32): error TS2345: Argument of type '{ sync: tru src/doc/doc-printer.js(213,17): error TS2532: Object is possibly 'undefined'. src/doc/doc-printer.js(214,18): error TS2532: Object is possibly 'undefined'. src/doc/doc-printer.js(215,17): error TS2532: Object is possibly 'undefined'. +src/doc/doc-printer.js(447,37): error TS2345: Argument of type 'any[][]' is not assignable to parameter of type 'never[]'. + Type 'any[]' is not assignable to type 'never'. src/language-css/clean.js(3,30): error TS2307: Cannot find module 'html-tag-names'. src/language-css/parser-postcss.js(78,32): error TS2345: Argument of type '{ groups: never[]; type: string; }' is not assignable to parameter of type 'never'. src/language-css/parser-postcss.js(88,30): error TS2345: Argument of type '{ open: null; close: null; groups: never[]; type: string; }' is not assignable to parameter of type 'never'. diff --git a/tests/baselines/reference/user/puppeteer.log b/tests/baselines/reference/user/puppeteer.log index 086229172aa..a3234ff8d98 100644 --- a/tests/baselines/reference/user/puppeteer.log +++ b/tests/baselines/reference/user/puppeteer.log @@ -1,17 +1,16 @@ Exit Code: 1 Standard output: -lib/Browser.js(71,43): error TS2345: Argument of type '() => Promise' is not assignable to parameter of type '() => Promise'. - Type 'Promise' is not assignable to type 'Promise'. - Type 'CDPSession' is not assignable to type 'Puppeteer.CDPSession'. - Types of property 'on' are incompatible. - Type '(event: string | symbol, listener: (...args: any[]) => void) => CDPSession' is not assignable to type '(event: T, listener: (arg: any) => void) => CDPSession'. - Types of parameters 'event' and 'event' are incompatible. - Type 'T' is not assignable to type 'string | symbol'. - Type 'string | number | symbol' is not assignable to type 'string | symbol'. - Type 'number' is not assignable to type 'string | symbol'. - Type 'T' is not assignable to type 'symbol'. - Type 'string | number | symbol' is not assignable to type 'symbol'. - Type 'string' is not assignable to type 'symbol'. +lib/Browser.js(71,49): error TS2322: Type 'Promise' is not assignable to type 'Promise'. + Type 'CDPSession' is not assignable to type 'Puppeteer.CDPSession'. + Types of property 'on' are incompatible. + Type '(event: string | symbol, listener: (...args: any[]) => void) => CDPSession' is not assignable to type '(event: T, listener: (arg: any) => void) => CDPSession'. + Types of parameters 'event' and 'event' are incompatible. + Type 'T' is not assignable to type 'string | symbol'. + Type 'string | number | symbol' is not assignable to type 'string | symbol'. + Type 'number' is not assignable to type 'string | symbol'. + Type 'T' is not assignable to type 'symbol'. + Type 'string | number | symbol' is not assignable to type 'symbol'. + Type 'string' is not assignable to type 'symbol'. lib/Coverage.js(109,15): error TS2503: Cannot find namespace 'Protocol'. lib/Coverage.js(196,15): error TS2503: Cannot find namespace 'Protocol'. lib/ElementHandle.js(24,15): error TS2503: Cannot find namespace 'Protocol'. @@ -52,7 +51,6 @@ lib/Page.js(935,3): error TS2322: Type '{ width: number; height: number; }' is n lib/Page.js(936,3): error TS2322: Type '{ width: number; height: number; }' is not assignable to type 'string'. lib/Page.js(937,3): error TS2322: Type '{ width: number; height: number; }' is not assignable to type 'string'. lib/Page.js(938,3): error TS2322: Type '{ width: number; height: number; }' is not assignable to type 'string'. -lib/externs.d.ts(2,30): error TS2497: Module '"/puppeteer/puppeteer/lib/Browser"' resolves to a non-module entity and cannot be imported using this construct. lib/externs.d.ts(3,29): error TS2497: Module '"/puppeteer/puppeteer/lib/Target"' resolves to a non-module entity and cannot be imported using this construct. lib/externs.d.ts(5,32): error TS2497: Module '"/puppeteer/puppeteer/lib/TaskQueue"' resolves to a non-module entity and cannot be imported using this construct. lib/externs.d.ts(9,37): error TS2497: Module '"/puppeteer/puppeteer/lib/ElementHandle"' resolves to a non-module entity and cannot be imported using this construct. diff --git a/tests/baselines/reference/user/uglify-js.log b/tests/baselines/reference/user/uglify-js.log index 2ba94206d96..5bd01b81213 100644 --- a/tests/baselines/reference/user/uglify-js.log +++ b/tests/baselines/reference/user/uglify-js.log @@ -4,6 +4,10 @@ node_modules/uglify-js/lib/ast.js(207,23): error TS2554: Expected 0 arguments, b node_modules/uglify-js/lib/ast.js(328,33): error TS2339: Property 'transform' does not exist on type 'string'. node_modules/uglify-js/lib/ast.js(869,5): error TS2322: Type '{ _visit: (node: any, descend: any) => any; parent: (n: any) => any; push: typeof push; pop: typeof pop; self: () => any; find_parent: (type: any) => any; has_directive: (type: any) => any; loopcontrol_target: (node: any) => any; in_boolean_context: () => boolean | undefined; }' is not assignable to type 'TreeWalker'. Object literal may only specify known properties, but '_visit' does not exist in type 'TreeWalker'. Did you mean to write 'visit'? +node_modules/uglify-js/lib/ast.js(870,14): error TS2339: Property 'push' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(877,14): error TS2339: Property 'pop' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(932,25): error TS2339: Property 'self' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(933,37): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. node_modules/uglify-js/lib/compress.js(167,27): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(500,26): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(817,18): error TS2554: Expected 0 arguments, but got 1. @@ -18,7 +22,11 @@ node_modules/uglify-js/lib/compress.js(1316,38): error TS2554: Expected 0 argume node_modules/uglify-js/lib/compress.js(1411,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. node_modules/uglify-js/lib/compress.js(1519,27): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(1551,26): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1652,49): error TS2345: Argument of type 'number[]' is not assignable to parameter of type '[number, number, ...never[]]'. + Property '0' is missing in type 'number[]'. node_modules/uglify-js/lib/compress.js(1975,44): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(2013,53): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[number, number, ...never[]]'. + Property '0' is missing in type 'any[]'. node_modules/uglify-js/lib/compress.js(2161,19): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(3214,23): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(3227,33): error TS2322: Type '"f"' is not assignable to type 'boolean'. @@ -29,12 +37,14 @@ node_modules/uglify-js/lib/compress.js(3464,62): error TS2554: Expected 0 argume node_modules/uglify-js/lib/compress.js(3690,23): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(3711,24): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. node_modules/uglify-js/lib/compress.js(3721,28): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(3880,21): error TS2403: Subsequent variable declarations must have the same type. Variable 'defs' must be of type 'Dictionary & { set: (key: any, val: any) => any; add: (key: any, val: any) => any; get: (key: any) => any; del: (key: any) => any; has: (key: any) => boolean; each: (f: any) => void; size: () => any; map: (f: any) => any[]; clone: () => Dictionary & any; toObject: () => any; }', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(3880,21): error TS2403: Subsequent variable declarations must have the same type. Variable 'defs' must be of type 'Dictionary & { set: (key: any, val: any) => Dictionary & any; add: (key: any, val: any) => Dictionary & any; get: (key: any) => any; del: (key: any) => Dictionary & any; has: (key: any) => boolean; ... 4 more ...; toObject: () => any; }', but here has type 'any'. node_modules/uglify-js/lib/compress.js(3932,17): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. node_modules/uglify-js/lib/compress.js(3988,30): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(4097,18): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(4396,17): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. node_modules/uglify-js/lib/compress.js(4480,22): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4672,57): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[RegExp, (string | undefined)?]'. + Property '0' is missing in type 'any[]'. node_modules/uglify-js/lib/compress.js(4830,30): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(4837,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'code' must be of type 'string', but here has type '{ get: () => string; toString: () => string; indent: () => void; indentation: () => number; current_width: () => number; should_break: () => boolean; has_parens: () => boolean; newline: () => void; print: (str: any) => void; ... 24 more ...; parent: (n: any) => any; }'. node_modules/uglify-js/lib/compress.js(4841,36): error TS2532: Object is possibly 'undefined'. @@ -100,6 +110,9 @@ node_modules/uglify-js/lib/sourcemap.js(55,25): error TS2304: Cannot find name ' node_modules/uglify-js/lib/sourcemap.js(61,23): error TS2304: Cannot find name 'MOZ_SourceMap'. node_modules/uglify-js/tools/exit.js(7,32): error TS2339: Property 'bufferSize' does not exist on type 'WriteStream'. node_modules/uglify-js/tools/exit.js(7,61): error TS2339: Property 'bufferSize' does not exist on type 'WriteStream'. +node_modules/uglify-js/tools/exit.js(10,37): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[(number | undefined)?]'. + Types of property 'length' are incompatible. + Type 'number' is not assignable to type '0 | 1'. node_modules/uglify-js/tools/node.js(64,26): error TS2339: Property 'minify' does not exist on type 'typeof import("/uglify-js/node_modules/uglify-js/tools/node")'. diff --git a/tests/baselines/reference/user/util.log b/tests/baselines/reference/user/util.log index 743d8d5e332..6440d2f326b 100644 --- a/tests/baselines/reference/user/util.log +++ b/tests/baselines/reference/user/util.log @@ -8,6 +8,9 @@ node_modules/util/util.js(55,20): error TS2555: Expected at least 2 arguments, b node_modules/util/util.js(73,15): error TS2339: Property 'noDeprecation' does not exist on type 'Process'. node_modules/util/util.js(80,19): error TS2339: Property 'throwDeprecation' does not exist on type 'Process'. node_modules/util/util.js(82,26): error TS2339: Property 'traceDeprecation' does not exist on type 'Process'. +node_modules/util/util.js(106,49): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, ...any[]]'. +node_modules/util/util.js(553,69): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, ...any[]]'. + Property 'pop' is missing in type 'IArguments'. diff --git a/tests/baselines/reference/validUseOfThisInSuper.js b/tests/baselines/reference/validUseOfThisInSuper.js index f4b83515417..d35b84f3df1 100644 --- a/tests/baselines/reference/validUseOfThisInSuper.js +++ b/tests/baselines/reference/validUseOfThisInSuper.js @@ -16,7 +16,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/varArgsOnConstructorTypes.js b/tests/baselines/reference/varArgsOnConstructorTypes.js index 499650a4ad3..bd99b74f8cb 100644 --- a/tests/baselines/reference/varArgsOnConstructorTypes.js +++ b/tests/baselines/reference/varArgsOnConstructorTypes.js @@ -31,7 +31,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } diff --git a/tests/baselines/reference/voidReturnIndexUnionInference.js b/tests/baselines/reference/voidReturnIndexUnionInference.js new file mode 100644 index 00000000000..01fcad76032 --- /dev/null +++ b/tests/baselines/reference/voidReturnIndexUnionInference.js @@ -0,0 +1,45 @@ +//// [voidReturnIndexUnionInference.ts] +// repro from https://github.com/Microsoft/TypeScript/issues/25274 +export function safeInvoke( + func: ((arg1: A1) => R) | null | undefined, + arg1: A1 +): R | undefined { + if (func) { + return func(arg1); + } else { + return undefined; + } +} + +interface Props { + onFoo?(value: string): boolean; + onBar?(value: string): void; +} + +function bad

(props: Readonly

) { + safeInvoke(props.onFoo, "blah"); + // ERROR HERE!!! + // Type R in signature of safeInvoke incorrectly inferred as {} instead of void! + safeInvoke(props.onBar, "blah"); +} + + +//// [voidReturnIndexUnionInference.js] +"use strict"; +exports.__esModule = true; +// repro from https://github.com/Microsoft/TypeScript/issues/25274 +function safeInvoke(func, arg1) { + if (func) { + return func(arg1); + } + else { + return undefined; + } +} +exports.safeInvoke = safeInvoke; +function bad(props) { + safeInvoke(props.onFoo, "blah"); + // ERROR HERE!!! + // Type R in signature of safeInvoke incorrectly inferred as {} instead of void! + safeInvoke(props.onBar, "blah"); +} diff --git a/tests/baselines/reference/voidReturnIndexUnionInference.symbols b/tests/baselines/reference/voidReturnIndexUnionInference.symbols new file mode 100644 index 00000000000..9a1cf9477d1 --- /dev/null +++ b/tests/baselines/reference/voidReturnIndexUnionInference.symbols @@ -0,0 +1,68 @@ +=== tests/cases/compiler/voidReturnIndexUnionInference.ts === +// repro from https://github.com/Microsoft/TypeScript/issues/25274 +export function safeInvoke( +>safeInvoke : Symbol(safeInvoke, Decl(voidReturnIndexUnionInference.ts, 0, 0)) +>A1 : Symbol(A1, Decl(voidReturnIndexUnionInference.ts, 1, 27)) +>R : Symbol(R, Decl(voidReturnIndexUnionInference.ts, 1, 30)) + + func: ((arg1: A1) => R) | null | undefined, +>func : Symbol(func, Decl(voidReturnIndexUnionInference.ts, 1, 34)) +>arg1 : Symbol(arg1, Decl(voidReturnIndexUnionInference.ts, 2, 12)) +>A1 : Symbol(A1, Decl(voidReturnIndexUnionInference.ts, 1, 27)) +>R : Symbol(R, Decl(voidReturnIndexUnionInference.ts, 1, 30)) + + arg1: A1 +>arg1 : Symbol(arg1, Decl(voidReturnIndexUnionInference.ts, 2, 47)) +>A1 : Symbol(A1, Decl(voidReturnIndexUnionInference.ts, 1, 27)) + +): R | undefined { +>R : Symbol(R, Decl(voidReturnIndexUnionInference.ts, 1, 30)) + + if (func) { +>func : Symbol(func, Decl(voidReturnIndexUnionInference.ts, 1, 34)) + + return func(arg1); +>func : Symbol(func, Decl(voidReturnIndexUnionInference.ts, 1, 34)) +>arg1 : Symbol(arg1, Decl(voidReturnIndexUnionInference.ts, 2, 47)) + + } else { + return undefined; +>undefined : Symbol(undefined) + } +} + +interface Props { +>Props : Symbol(Props, Decl(voidReturnIndexUnionInference.ts, 10, 1)) + + onFoo?(value: string): boolean; +>onFoo : Symbol(Props.onFoo, Decl(voidReturnIndexUnionInference.ts, 12, 17)) +>value : Symbol(value, Decl(voidReturnIndexUnionInference.ts, 13, 11)) + + onBar?(value: string): void; +>onBar : Symbol(Props.onBar, Decl(voidReturnIndexUnionInference.ts, 13, 35)) +>value : Symbol(value, Decl(voidReturnIndexUnionInference.ts, 14, 11)) +} + +function bad

(props: Readonly

) { +>bad : Symbol(bad, Decl(voidReturnIndexUnionInference.ts, 15, 1)) +>P : Symbol(P, Decl(voidReturnIndexUnionInference.ts, 17, 13)) +>Props : Symbol(Props, Decl(voidReturnIndexUnionInference.ts, 10, 1)) +>props : Symbol(props, Decl(voidReturnIndexUnionInference.ts, 17, 30)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>P : Symbol(P, Decl(voidReturnIndexUnionInference.ts, 17, 13)) + + safeInvoke(props.onFoo, "blah"); +>safeInvoke : Symbol(safeInvoke, Decl(voidReturnIndexUnionInference.ts, 0, 0)) +>props.onFoo : Symbol(onFoo, Decl(voidReturnIndexUnionInference.ts, 12, 17)) +>props : Symbol(props, Decl(voidReturnIndexUnionInference.ts, 17, 30)) +>onFoo : Symbol(onFoo, Decl(voidReturnIndexUnionInference.ts, 12, 17)) + + // ERROR HERE!!! + // Type R in signature of safeInvoke incorrectly inferred as {} instead of void! + safeInvoke(props.onBar, "blah"); +>safeInvoke : Symbol(safeInvoke, Decl(voidReturnIndexUnionInference.ts, 0, 0)) +>props.onBar : Symbol(onBar, Decl(voidReturnIndexUnionInference.ts, 13, 35)) +>props : Symbol(props, Decl(voidReturnIndexUnionInference.ts, 17, 30)) +>onBar : Symbol(onBar, Decl(voidReturnIndexUnionInference.ts, 13, 35)) +} + diff --git a/tests/baselines/reference/voidReturnIndexUnionInference.types b/tests/baselines/reference/voidReturnIndexUnionInference.types new file mode 100644 index 00000000000..20a962b9fef --- /dev/null +++ b/tests/baselines/reference/voidReturnIndexUnionInference.types @@ -0,0 +1,61 @@ +=== tests/cases/compiler/voidReturnIndexUnionInference.ts === +// repro from https://github.com/Microsoft/TypeScript/issues/25274 +export function safeInvoke( +>safeInvoke : (func: ((arg1: A1) => R) | null | undefined, arg1: A1) => R | undefined + + func: ((arg1: A1) => R) | null | undefined, +>func : ((arg1: A1) => R) | null | undefined +>arg1 : A1 +>null : null + + arg1: A1 +>arg1 : A1 + +): R | undefined { + if (func) { +>func : ((arg1: A1) => R) | null | undefined + + return func(arg1); +>func(arg1) : R +>func : (arg1: A1) => R +>arg1 : A1 + + } else { + return undefined; +>undefined : undefined + } +} + +interface Props { + onFoo?(value: string): boolean; +>onFoo : ((value: string) => boolean) | undefined +>value : string + + onBar?(value: string): void; +>onBar : ((value: string) => void) | undefined +>value : string +} + +function bad

(props: Readonly

) { +>bad :

(props: Readonly

) => void +>props : Readonly

+ + safeInvoke(props.onFoo, "blah"); +>safeInvoke(props.onFoo, "blah") : boolean | undefined +>safeInvoke : (func: ((arg1: A1) => R) | null | undefined, arg1: A1) => R | undefined +>props.onFoo : P["onFoo"] +>props : Readonly

+>onFoo : P["onFoo"] +>"blah" : "blah" + + // ERROR HERE!!! + // Type R in signature of safeInvoke incorrectly inferred as {} instead of void! + safeInvoke(props.onBar, "blah"); +>safeInvoke(props.onBar, "blah") : void | undefined +>safeInvoke : (func: ((arg1: A1) => R) | null | undefined, arg1: A1) => R | undefined +>props.onBar : P["onBar"] +>props : Readonly

+>onBar : P["onBar"] +>"blah" : "blah" +} + diff --git a/tests/baselines/reference/weakType.errors.txt b/tests/baselines/reference/weakType.errors.txt index ffc1d237593..4ea859a82dd 100644 --- a/tests/baselines/reference/weakType.errors.txt +++ b/tests/baselines/reference/weakType.errors.txt @@ -29,12 +29,15 @@ tests/cases/compiler/weakType.ts(62,5): error TS2322: Type '{ properties: { wron doSomething(getDefaultSettings); ~~~~~~~~~~~~~~~~~~ !!! error TS2560: Value of type '() => { timeout: number; }' has no properties in common with type 'Settings'. Did you mean to call it? +!!! related TS6212 tests/cases/compiler/weakType.ts:15:13: Did you mean to call this expression? doSomething(() => ({ timeout: 1000 })); ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2560: Value of type '() => { timeout: number; }' has no properties in common with type 'Settings'. Did you mean to call it? +!!! related TS6212 tests/cases/compiler/weakType.ts:16:13: Did you mean to call this expression? doSomething(null as CtorOnly); ~~~~~~~~~~~~~~~~ !!! error TS2560: Value of type 'CtorOnly' has no properties in common with type 'Settings'. Did you mean to call it? +!!! related TS6213 tests/cases/compiler/weakType.ts:17:13: Did you mean to use 'new' with this expression? doSomething(12); ~~ !!! error TS2559: Type '12' has no properties in common with type 'Settings'. diff --git a/tests/baselines/reference/widenedTypes.errors.txt b/tests/baselines/reference/widenedTypes.errors.txt index aac9627adeb..fb6779ff0eb 100644 --- a/tests/baselines/reference/widenedTypes.errors.txt +++ b/tests/baselines/reference/widenedTypes.errors.txt @@ -5,8 +5,7 @@ tests/cases/compiler/widenedTypes.ts(7,15): error TS2531: Object is possibly 'nu tests/cases/compiler/widenedTypes.ts(9,14): error TS2695: Left side of comma operator is unused and has no side effects. tests/cases/compiler/widenedTypes.ts(10,1): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/compiler/widenedTypes.ts(17,1): error TS2322: Type '""' is not assignable to type 'number'. -tests/cases/compiler/widenedTypes.ts(22,5): error TS2322: Type 'number[]' is not assignable to type 'string[]'. - Type 'number' is not assignable to type 'string'. +tests/cases/compiler/widenedTypes.ts(22,22): error TS2322: Type 'number' is not assignable to type 'string'. tests/cases/compiler/widenedTypes.ts(23,39): error TS2322: Type 'number' is not assignable to type 'string'. @@ -47,9 +46,8 @@ tests/cases/compiler/widenedTypes.ts(23,39): error TS2322: Type 'number' is not // Highlights the difference between array literals and object literals var arr: string[] = [3, null]; // not assignable because null is not widened. BCT is {} - ~~~ -!!! error TS2322: Type 'number[]' is not assignable to type 'string[]'. -!!! error TS2322: Type 'number' is not assignable to type 'string'. + ~ +!!! error TS2322: Type 'number' is not assignable to type 'string'. var obj: { [x: string]: string; } = { x: 3, y: null }; // assignable because null is widened, and therefore BCT is any ~ !!! error TS2322: Type 'number' is not assignable to type 'string'. diff --git a/tests/baselines/reference/wrappedAndRecursiveConstraints4.errors.txt b/tests/baselines/reference/wrappedAndRecursiveConstraints4.errors.txt index 65bfc5b20d5..4b19087eea0 100644 --- a/tests/baselines/reference/wrappedAndRecursiveConstraints4.errors.txt +++ b/tests/baselines/reference/wrappedAndRecursiveConstraints4.errors.txt @@ -18,5 +18,4 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/wrappedAndRecursi var r2 = r({ length: 3, charAt: (x: number) => { '' } }); // error ~~~~~~ !!! error TS2322: Type '(x: number) => void' is not assignable to type '(pos: number) => string'. -!!! error TS2322: Type 'void' is not assignable to type 'string'. -!!! related TS6500 /.ts/lib.es5.d.ts:332:5: The expected type comes from property 'charAt' which is declared here on type 'string' \ No newline at end of file +!!! error TS2322: Type 'void' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/cases/compiler/abstractPropertyInConstructor.ts b/tests/cases/compiler/abstractPropertyInConstructor.ts index 5ea3569e20d..a665431bb4e 100644 --- a/tests/cases/compiler/abstractPropertyInConstructor.ts +++ b/tests/cases/compiler/abstractPropertyInConstructor.ts @@ -30,6 +30,36 @@ abstract class AbstractClass { } } +abstract class DerivedAbstractClass extends AbstractClass { + cb = (s: string) => {}; + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { + super(str, other); + // there is no implementation of 'prop' in any base class + this.cb(this.prop.toLowerCase()); + + this.method(1); + + // OK, references are to another instance + other.cb(other.prop); + yetAnother.cb(yetAnother.prop); + } +} + +class Implementation extends DerivedAbstractClass { + prop = ""; + cb = (s: string) => {}; + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { + super(str, other, yetAnother); + this.cb(this.prop); + } + + method(n: number) { + this.cb(this.prop + n); + } +} + class User { constructor(a: AbstractClass) { a.prop; diff --git a/tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts b/tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts new file mode 100644 index 00000000000..c82b8c493cc --- /dev/null +++ b/tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts @@ -0,0 +1,7 @@ +function foo(a, b, {c}): void {} + +function bar(a, b, [c]): void {} + +foo("", 0); + +bar("", 0); diff --git a/tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts b/tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts new file mode 100644 index 00000000000..42c3025c8e3 --- /dev/null +++ b/tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts @@ -0,0 +1,14 @@ +declare function foo(): string; + +foo()(1 as number).toString(); + +foo() (1 as number).toString(); + +foo() +(1 as number).toString(); + +foo() + (1 as number).toString(); + +foo() + (1).toString(); diff --git a/tests/cases/compiler/capturedLetConstInLoop1.ts b/tests/cases/compiler/capturedLetConstInLoop1.ts index e4956fd16df..4919429eec7 100644 --- a/tests/cases/compiler/capturedLetConstInLoop1.ts +++ b/tests/cases/compiler/capturedLetConstInLoop1.ts @@ -1,3 +1,5 @@ +declare function use(x: any): any; + //==== let for (let x in {}) { (function() { return x}); @@ -55,6 +57,19 @@ for (let y = 0; y < 1; ++y) { (() => x + y); } +for (let y = (use(() => y), 0); y < 1; ++y) { +} + +for (let y = 0; use(() => y), y < 1; ++y) { +} + +for (let y = 0; y < 1; use(() => y), ++y) { +} + +for (let y = (use(() => y), 0); use(() => y), y < 1; use(() => y), ++y) { + use(() => y); +} + //=========const for (const x in {}) { (function() { return x}); diff --git a/tests/cases/compiler/complicatedIndexesOfIntersectionsAreInferencable.ts b/tests/cases/compiler/complicatedIndexesOfIntersectionsAreInferencable.ts new file mode 100644 index 00000000000..650d8886cae --- /dev/null +++ b/tests/cases/compiler/complicatedIndexesOfIntersectionsAreInferencable.ts @@ -0,0 +1,22 @@ +// @strict: true +interface FormikConfig { + initialValues: Values; + validate?: (props: Values) => void; + validateOnChange?: boolean; +} + +declare function Func( + x: (string extends "validate" | "initialValues" | keyof ExtraProps + ? Readonly & ExtraProps> + : Pick & ExtraProps>, "validate" | "initialValues" | Exclude> + & Partial & ExtraProps>, "validateOnChange" | Extract>>) +): void; + +Func({ + initialValues: { + foo: "" + }, + validate: props => { + props.foo; + } +}); \ No newline at end of file diff --git a/tests/cases/compiler/conditionalTypeContextualTypeSimplificationsSuceeds.ts b/tests/cases/compiler/conditionalTypeContextualTypeSimplificationsSuceeds.ts new file mode 100644 index 00000000000..f585022cccf --- /dev/null +++ b/tests/cases/compiler/conditionalTypeContextualTypeSimplificationsSuceeds.ts @@ -0,0 +1,16 @@ +// @strict: true +// repro from https://github.com/Microsoft/TypeScript/issues/26395 +interface Props { + when: (value: string) => boolean; +} + +function bad

( + attrs: string extends keyof P ? { [K in keyof P]: P[K] } : { [K in keyof P]: P[K] }) { } +function good1

( + attrs: string extends keyof P ? P : { [K in keyof P]: P[K] }) { } +function good2

( + attrs: { [K in keyof P]: P[K] }) { } + +bad({ when: value => false }); +good1({ when: value => false }); +good2({ when: value => false }); \ No newline at end of file diff --git a/tests/cases/compiler/contextualTypeOfIndexedAccessParameter.ts b/tests/cases/compiler/contextualTypeOfIndexedAccessParameter.ts new file mode 100644 index 00000000000..2135ed5cb29 --- /dev/null +++ b/tests/cases/compiler/contextualTypeOfIndexedAccessParameter.ts @@ -0,0 +1,15 @@ +// @strict: true +type Keys = "a" | "b"; + +type OptionsForKey = { a: { cb: (p: number) => number } } & { b: {} }; + +declare function f(key: K, options: OptionsForKey[K]): void; + +f("a", { + cb: p => p, +}); + +function g< + K extends "a" | "b">(x: ({ a: string } & { b: string })[K], y: string) { + x = y; +} diff --git a/tests/cases/compiler/controlFlowInstanceof.ts b/tests/cases/compiler/controlFlowInstanceof.ts index 56f3ff97e4c..b032fb708dc 100644 --- a/tests/cases/compiler/controlFlowInstanceof.ts +++ b/tests/cases/compiler/controlFlowInstanceof.ts @@ -1,5 +1,10 @@ // @target: es6 +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @strictNullChecks: true +// @Filename: controlFlowInstanceof.ts // Repros from #10167 function f1(s: Set | Set) { @@ -96,4 +101,23 @@ function goo(x: X) { x.y; } x; -} \ No newline at end of file +} + +// Repro from #27282 + +declare const x: (() => void)|null; +declare const ctor: Function; + +if (x instanceof ctor) { + x(); +} + +// Repro from #27550 (based on uglify code) +// @Filename: uglify.js +/** @constructor */ +function AtTop(val) { this.val = val } +/** @type {*} */ +var v = 1; +if (v instanceof AtTop) { + v.val +} diff --git a/tests/cases/compiler/declarationEmitNoNonRequiredParens.ts b/tests/cases/compiler/declarationEmitNoNonRequiredParens.ts new file mode 100644 index 00000000000..020fd785c40 --- /dev/null +++ b/tests/cases/compiler/declarationEmitNoNonRequiredParens.ts @@ -0,0 +1,8 @@ +// @declaration: true +export enum Test { + A, B, C +} + +export type TestType = typeof Test; + +export const bar = (null as TestType[Extract][]); \ No newline at end of file diff --git a/tests/cases/compiler/declarationEmitOfFuncspace.ts b/tests/cases/compiler/declarationEmitOfFuncspace.ts new file mode 100644 index 00000000000..9648178ae81 --- /dev/null +++ b/tests/cases/compiler/declarationEmitOfFuncspace.ts @@ -0,0 +1,9 @@ +// @declaration: true +// @Filename: expando.ts +// #27032 +function ExpandoMerge(n: number) { + return n; +} +namespace ExpandoMerge { + export interface I { } +} diff --git a/tests/cases/compiler/declarationEmitToDeclarationDirWithCompositeOption.ts b/tests/cases/compiler/declarationEmitToDeclarationDirWithCompositeOption.ts new file mode 100644 index 00000000000..77a4c3099cf --- /dev/null +++ b/tests/cases/compiler/declarationEmitToDeclarationDirWithCompositeOption.ts @@ -0,0 +1,11 @@ +// @composite: true +// @filename: /foo/tsconfig.json +{ + "compilerOptions": { "composite": true, "declarationDir": "out" } +} + +// @filename: /foo/test.ts +interface Foo { + x: number; +} +export default Foo; diff --git a/tests/cases/compiler/declarationEmitToDeclarationDirWithDeclarationOption.ts b/tests/cases/compiler/declarationEmitToDeclarationDirWithDeclarationOption.ts new file mode 100644 index 00000000000..e3d4231a8f6 --- /dev/null +++ b/tests/cases/compiler/declarationEmitToDeclarationDirWithDeclarationOption.ts @@ -0,0 +1,11 @@ +// @declaration: true +// @filename: /foo/tsconfig.json +{ + "compilerOptions": { "declaration": true, "declarationDir": "out" } +} + +// @filename: /foo/test.ts +interface Foo { + x: number; +} +export default Foo; diff --git a/tests/cases/compiler/declarationEmitToDeclarationDirWithoutCompositeAndDeclarationOptions.ts b/tests/cases/compiler/declarationEmitToDeclarationDirWithoutCompositeAndDeclarationOptions.ts new file mode 100644 index 00000000000..08405e5fc96 --- /dev/null +++ b/tests/cases/compiler/declarationEmitToDeclarationDirWithoutCompositeAndDeclarationOptions.ts @@ -0,0 +1,10 @@ +// @filename: /foo/tsconfig.json +{ + "compilerOptions": { "declarationDir": "out" } +} + +// @filename: /foo/test.ts +interface Foo { + x: number; +} +export default Foo; diff --git a/tests/cases/compiler/declarationTypecheckNoUseBeforeReferenceCheck.ts b/tests/cases/compiler/declarationTypecheckNoUseBeforeReferenceCheck.ts new file mode 100644 index 00000000000..21c1db5f59c --- /dev/null +++ b/tests/cases/compiler/declarationTypecheckNoUseBeforeReferenceCheck.ts @@ -0,0 +1,5 @@ +// @filename: index.d.ts +export class C extends Object { + static readonly p: unique symbol; + [C.p](): void; +} \ No newline at end of file diff --git a/tests/cases/compiler/deepElaborationsIntoArrowExpressions.ts b/tests/cases/compiler/deepElaborationsIntoArrowExpressions.ts new file mode 100644 index 00000000000..283c9424388 --- /dev/null +++ b/tests/cases/compiler/deepElaborationsIntoArrowExpressions.ts @@ -0,0 +1,19 @@ +// @target: es6 +const a: { + y(): "a" +} = { + y: () => "b" +}; + +interface Foo { + a: number; +} + +function foo1(): () => Foo { + return () => ({a: ''}); +} + +function foo3(): Foo[] { + return [{a: ''}]; +} +var y: Foo[] = [{a: ''}] \ No newline at end of file diff --git a/tests/cases/compiler/destructuringTuple.ts b/tests/cases/compiler/destructuringTuple.ts new file mode 100644 index 00000000000..c6a8431da0b --- /dev/null +++ b/tests/cases/compiler/destructuringTuple.ts @@ -0,0 +1,9 @@ +// @strict: true + +declare var tuple: [boolean, number, ...string[]]; + +const [a, b, c, ...rest] = tuple; + +declare var receiver: typeof tuple; + +[...receiver] = tuple; diff --git a/tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts b/tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts new file mode 100644 index 00000000000..392f3461d9a --- /dev/null +++ b/tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts @@ -0,0 +1,27 @@ +class Bar { + x!: string; +} + +declare function getNum(): number; + +declare function foo(arg: { x: Bar, y: Date }, item: number, items?: [number, number, number]): void; + +foo({ + x: Bar, + y: Date +}, getNum()); + +foo({ + x: new Bar(), + y: new Date() +}, getNum); + + +foo({ + x: new Bar(), + y: new Date() +}, getNum(), [ + 1, + 2, + getNum +]); diff --git a/tests/cases/compiler/didYouMeanSuggestionErrors.ts b/tests/cases/compiler/didYouMeanSuggestionErrors.ts new file mode 100644 index 00000000000..d5af5a338d3 --- /dev/null +++ b/tests/cases/compiler/didYouMeanSuggestionErrors.ts @@ -0,0 +1,29 @@ +// @lib: es5 +describe("my test suite", () => { + it("should run", () => { + const a = $(".thing"); + }); +}); + +suite("another suite", () => { + test("everything else", () => { + console.log(process.env); + document.createElement("div"); + + const x = require("fs"); + const y = Buffer.from([]); + const z = module.exports; + + const a = new Map(); + const b = new Set(); + const c = new WeakMap(); + const d = new WeakSet(); + const e = Symbol(); + const f = Promise.resolve(0); + + const i: Iterator = null as any; + const j: AsyncIterator = null as any; + const k: Symbol = null as any; + const l: Promise = null as any; + }); +}); \ No newline at end of file diff --git a/tests/cases/compiler/discriminantPropertyCheck.ts b/tests/cases/compiler/discriminantPropertyCheck.ts index e493f6bf770..16fb847bdf0 100644 --- a/tests/cases/compiler/discriminantPropertyCheck.ts +++ b/tests/cases/compiler/discriminantPropertyCheck.ts @@ -66,4 +66,36 @@ function foo6(x: Item) { if (x.foo !== undefined && x.qux) { x.foo.length; // Error, intervening discriminant guard } -} \ No newline at end of file +} + +// Repro from #27493 + +enum Types { Str = 1, Num = 2 } + +type Instance = StrType | NumType; + +interface StrType { + type: Types.Str; + value: string; + length: number; +} + +interface NumType { + type: Types.Num; + value: number; +} + +function func2(inst: Instance) { + while (true) { + switch (inst.type) { + case Types.Str: { + inst.value.length; + break; + } + case Types.Num: { + inst.value.toExponential; + break; + } + } + } +} diff --git a/tests/cases/compiler/duplicateIdentifierRelatedSpans_moduleAugmentation.ts b/tests/cases/compiler/duplicateIdentifierRelatedSpans_moduleAugmentation.ts new file mode 100644 index 00000000000..8df0b66da60 --- /dev/null +++ b/tests/cases/compiler/duplicateIdentifierRelatedSpans_moduleAugmentation.ts @@ -0,0 +1,13 @@ +// @Filename: /dir/a.ts +export const x = 0; + +// @Filename: /dir/b.ts +export {}; + +declare module "./a" { + export const x = 0; +} + +declare module "../dir/a" { + export const x = 0; +} diff --git a/tests/cases/compiler/elaborationForPossiblyCallableTypeStillReferencesArgumentAtTopLevel.ts b/tests/cases/compiler/elaborationForPossiblyCallableTypeStillReferencesArgumentAtTopLevel.ts new file mode 100644 index 00000000000..f2b964fadbc --- /dev/null +++ b/tests/cases/compiler/elaborationForPossiblyCallableTypeStillReferencesArgumentAtTopLevel.ts @@ -0,0 +1,3 @@ +declare var ohno: new () => number; +declare function ff(t: number): void; +ff(ohno) \ No newline at end of file diff --git a/tests/cases/compiler/errorForConflictingExportEqualsValue.ts b/tests/cases/compiler/errorForConflictingExportEqualsValue.ts index 59af1f46690..a91ecc390b5 100644 --- a/tests/cases/compiler/errorForConflictingExportEqualsValue.ts +++ b/tests/cases/compiler/errorForConflictingExportEqualsValue.ts @@ -1,2 +1,5 @@ +// @lib: es6 +// @Filename: /a.ts export var x; -export = {}; +export = x; +import("./a"); diff --git a/tests/cases/compiler/esModuleInteropEnablesSyntheticDefaultImports.ts b/tests/cases/compiler/esModuleInteropEnablesSyntheticDefaultImports.ts new file mode 100644 index 00000000000..29042d8ea9f --- /dev/null +++ b/tests/cases/compiler/esModuleInteropEnablesSyntheticDefaultImports.ts @@ -0,0 +1,10 @@ +// @esModuleInterop: true +// @module: es2015 +// @Filename: a.ts +import Namespace from "./b"; +export var x = new Namespace.Foo(); + +// @Filename: b.d.ts +export class Foo { + member: string; +} diff --git a/tests/cases/compiler/exportDefaultStripsFreshness.ts b/tests/cases/compiler/exportDefaultStripsFreshness.ts new file mode 100644 index 00000000000..1a1bc0cc272 --- /dev/null +++ b/tests/cases/compiler/exportDefaultStripsFreshness.ts @@ -0,0 +1,21 @@ +// @filename: items.ts +export default { + foob: "a" +} + +export const q = { + foob: "b" +} +// @filename: index.ts +import B, {q} from "./items"; + +interface IFoo { + foo: string; +} + +function nFoo(x: IFoo) {} + + +nFoo(q); // for comparison + +nFoo(B); diff --git a/tests/cases/compiler/extractInferenceImprovement.ts b/tests/cases/compiler/extractInferenceImprovement.ts new file mode 100644 index 00000000000..f70e6c07e86 --- /dev/null +++ b/tests/cases/compiler/extractInferenceImprovement.ts @@ -0,0 +1,29 @@ +// @target: es6 +// repro mostly from https://github.com/Microsoft/TypeScript/issues/25065 +function getProperty2(obj: T, key: Extract): T[K] { + return obj[key]; +} + +function getProperty3>(obj: T, key: K): T[K] { + return obj[key]; +} + +const s = Symbol(); +interface StrNum { + first: string; + second: number; + [s]: string; +} +const obj: StrNum = {} as any; + +let prop: string; + +// should work +prop = getProperty2(obj, 'first'); + +prop = getProperty3(obj, 'first'); + +// Should fail +prop = getProperty2(obj, s); + +prop = getProperty3(obj, s); diff --git a/tests/cases/compiler/jsFileCompilationWithEnabledCompositeOption.ts b/tests/cases/compiler/jsFileCompilationWithEnabledCompositeOption.ts new file mode 100644 index 00000000000..90340ef5d3a --- /dev/null +++ b/tests/cases/compiler/jsFileCompilationWithEnabledCompositeOption.ts @@ -0,0 +1,10 @@ +// @allowJs: true +// @out: out.js +// @composite: true +// @filename: a.ts +class c { +} + +// @filename: b.js +function foo() { +} diff --git a/tests/cases/compiler/jsdocClassMissingTypeArguments.ts b/tests/cases/compiler/jsdocClassMissingTypeArguments.ts new file mode 100644 index 00000000000..7a8606d8237 --- /dev/null +++ b/tests/cases/compiler/jsdocClassMissingTypeArguments.ts @@ -0,0 +1,11 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true + +// @Filename: /a.js +/** @template T */ +class C {} + +/** @param {C} p */ +function f(p) {} diff --git a/tests/cases/compiler/jsdocInTypeScript.ts b/tests/cases/compiler/jsdocInTypeScript.ts index bceac17aa2c..4d1f0fbbe42 100644 --- a/tests/cases/compiler/jsdocInTypeScript.ts +++ b/tests/cases/compiler/jsdocInTypeScript.ts @@ -46,3 +46,7 @@ import M = N; // Error: @typedef does not create namespaces in TypeScript code. * @type {{foo: (function(string, string): string)}} */ const obj = { foo: (a, b) => a + b }; + +/** @enum {string} */ +var E = {}; +E[""]; diff --git a/tests/cases/compiler/jsdocUnexpectedCharacter.ts b/tests/cases/compiler/jsdocUnexpectedCharacter.ts new file mode 100644 index 00000000000..ef7a2f78c99 --- /dev/null +++ b/tests/cases/compiler/jsdocUnexpectedCharacter.ts @@ -0,0 +1,7 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true + +// @Filename: /a.js +/** @x # */ +var UI = {}; diff --git a/tests/cases/compiler/literalFreshnessPropagationOnNarrowing.ts b/tests/cases/compiler/literalFreshnessPropagationOnNarrowing.ts new file mode 100644 index 00000000000..56f14dc6b2b --- /dev/null +++ b/tests/cases/compiler/literalFreshnessPropagationOnNarrowing.ts @@ -0,0 +1,61 @@ +function f1() { + let b = true; + let obj = { b }; + // Desired: OK + // 3.0: OK + // 3.1 as-is: OK + // 3.1 minus widening propagation: error + obj.b = false; +} + +function f2() { + type Element = (string | false); + type ElementOrArray = Element | Element[]; + let el: Element = null as any; + let arr: Element[] = null as any; + let elOrA: ElementOrArray = null as any; + + // Desired/actual: All OK + let a1: ElementOrArray = el; + let a2: ElementOrArray = arr; + let a3: ElementOrArray = [el]; + let a4: ElementOrArray = Array.isArray(elOrA) ? elOrA : [elOrA]; + + // Desired: OK + // 3.0: Error + // 3.1: OK + let a5: ElementOrArray = [...Array.isArray(elOrA) ? elOrA : [elOrA]]; +} + +function f3() { + type XY = 'x' | 'y'; + const x: XY = 'x'; + let x2 = x; + // Desired: OK (up for debate?) + // 3.0: Error + // 3.1 as-is: OK + x2 = 'y'; + + // Desired/actual: All OK + let x3: XY = x; + x3 = 'y'; +} + +function f4() { + const x: boolean = true; + let x1 = x; + // Desired: OK + // 3.0: OK + // 3.1: OK + // 3.1 minus widening propagation: error + x1 = false; +} + +function f5() { + type XY = 'x' | 'y'; + let arr: XY[] = ['x']; + arr = ['y']; + // Desired: OK + // Error in all extant branches + arr = [...['y']]; +} \ No newline at end of file diff --git a/tests/cases/compiler/mappedTypeParameterConstraint.ts b/tests/cases/compiler/mappedTypeParameterConstraint.ts new file mode 100644 index 00000000000..16b37999c92 --- /dev/null +++ b/tests/cases/compiler/mappedTypeParameterConstraint.ts @@ -0,0 +1,6 @@ +// Repro for #27596 + +type MyMap = {[P in keyof T]: T[keyof T]}; +function foo(arg: U): MyMap { + return arg; +} diff --git a/tests/cases/compiler/moduleMemberMissingErrorIsRelative.ts b/tests/cases/compiler/moduleMemberMissingErrorIsRelative.ts new file mode 100644 index 00000000000..8cb8e1d2948 --- /dev/null +++ b/tests/cases/compiler/moduleMemberMissingErrorIsRelative.ts @@ -0,0 +1,4 @@ +// @filename: folder/foo.ts +export {}; +// @filename: folder/bar.ts +import {nosuch} from './foo'; \ No newline at end of file diff --git a/tests/cases/compiler/moduleResolution_automaticTypeDirectiveNames.ts b/tests/cases/compiler/moduleResolution_automaticTypeDirectiveNames.ts new file mode 100644 index 00000000000..b5baa1bbe16 --- /dev/null +++ b/tests/cases/compiler/moduleResolution_automaticTypeDirectiveNames.ts @@ -0,0 +1,10 @@ +// @noImplicitReferences: true + +// @Filename: /node_modules/@types/.a/index.d.ts +declare const a: number; + +// @Filename: /node_modules/@types/a/index.d.ts +declare const a: string; + +// @Filename: /a.ts +a; diff --git a/tests/cases/compiler/moduleResolution_noLeadingDot.ts b/tests/cases/compiler/moduleResolution_noLeadingDot.ts new file mode 100644 index 00000000000..eee17136b11 --- /dev/null +++ b/tests/cases/compiler/moduleResolution_noLeadingDot.ts @@ -0,0 +1,7 @@ +// @noImplicitReferences: true + +// @Filename: /node_modules/@types/.svn/README.md +This is a test. + +// @Filename: /a.ts +true; diff --git a/tests/cases/compiler/outModuleConcatCommonjsDeclarationOnly.ts b/tests/cases/compiler/outModuleConcatCommonjsDeclarationOnly.ts new file mode 100644 index 00000000000..aa662e337c9 --- /dev/null +++ b/tests/cases/compiler/outModuleConcatCommonjsDeclarationOnly.ts @@ -0,0 +1,13 @@ +// @target: ES5 +// @sourcemap: true +// @declaration: true +// @emitDeclarationOnly: true +// @module: commonjs +// @outFile: all.js + +// @Filename: ref/a.ts +export class A { } + +// @Filename: b.ts +import {A} from "./ref/a"; +export class B extends A { } \ No newline at end of file diff --git a/tests/cases/compiler/outModuleConcatUnspecifiedModuleKindDeclarationOnly.ts b/tests/cases/compiler/outModuleConcatUnspecifiedModuleKindDeclarationOnly.ts new file mode 100644 index 00000000000..862f64507a2 --- /dev/null +++ b/tests/cases/compiler/outModuleConcatUnspecifiedModuleKindDeclarationOnly.ts @@ -0,0 +1,10 @@ +// @target: ES5 +// @outFile: out.js +// @declaration: true +// @emitDeclarationOnly: true + +// @Filename: a.ts +export class A { } // module + +// @Filename: b.ts +var x = 0; // global \ No newline at end of file diff --git a/tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx b/tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx new file mode 100644 index 00000000000..d1ee95995b9 --- /dev/null +++ b/tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx @@ -0,0 +1,70 @@ +// @jsx: react +// @strict: true +// @esModuleInterop: true +/// + +import React from 'react'; + +interface BaseProps { + when?: ((value: string) => boolean) | "a" | "b"; + error?: boolean; +} + +interface Props extends BaseProps { +} + +class FieldFeedback

extends React.Component

{ + static defaultProps = { + when: () => true + }; + + render() { + return

Hello
; + } +} + +// OK +const Test1 = () => !!value} />; + +// Error: Void not assignable to boolean +const Test2 = () => console.log(value)} />; + +class FieldFeedbackBeta

extends React.Component

{ + static defaultProps: BaseProps = { + when: () => true + }; + + render() { + return

Hello
; + } +} + +// OK +const Test1a = () => !!value} error>Hah; + +// Error: Void not assignable to boolean +const Test2a = () => console.log(value)} error>Hah; + +interface MyPropsProps extends Props { + when: (value: string) => boolean; +} + +class FieldFeedback2

extends FieldFeedback

{ + static defaultProps = { + when: () => true + }; + + render() { + this.props.when("now"); // OK, always defined + return

Hello
; + } +} + +// OK +const Test3 = () => !!value} />; + +// Error: Void not assignable to boolean +const Test4 = () => console.log(value)} />; + +// OK +const Test5 = () => ; diff --git a/tests/cases/compiler/spreadBooleanRespectsFreshness.ts b/tests/cases/compiler/spreadBooleanRespectsFreshness.ts new file mode 100644 index 00000000000..ce9a58684b5 --- /dev/null +++ b/tests/cases/compiler/spreadBooleanRespectsFreshness.ts @@ -0,0 +1,7 @@ +type Foo = FooBase | FooArray; +type FooBase = string | false; +type FooArray = FooBase[]; + +declare let foo1: Foo; +declare let foo2: Foo; +foo1 = [...Array.isArray(foo2) ? foo2 : [foo2]]; \ No newline at end of file diff --git a/tests/cases/compiler/staticMismatchBecauseOfPrototype.ts b/tests/cases/compiler/staticMismatchBecauseOfPrototype.ts new file mode 100644 index 00000000000..24d50f1951d --- /dev/null +++ b/tests/cases/compiler/staticMismatchBecauseOfPrototype.ts @@ -0,0 +1,11 @@ +interface A { + n: number; +} +declare var A: { + prototype: A; + new(): A; +}; + +class B extends A { + n = ""; +} \ No newline at end of file diff --git a/tests/cases/compiler/strictBooleanMemberAssignability.ts b/tests/cases/compiler/strictBooleanMemberAssignability.ts new file mode 100644 index 00000000000..8b723c1de10 --- /dev/null +++ b/tests/cases/compiler/strictBooleanMemberAssignability.ts @@ -0,0 +1,7 @@ +// @strict: true +class Abc { + def: boolean + constructor() { + this.def = true + } +} \ No newline at end of file diff --git a/tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx b/tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx new file mode 100644 index 00000000000..beb6844117f --- /dev/null +++ b/tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx @@ -0,0 +1,22 @@ +// @jsx: react +// @strict: true +// @esModuleInterop: true +/// + +import React from 'react'; + +function test

(wrappedProps: P) { + let MySFC = function(props: P) { + return <>hello; + }; + class MyComponent extends React.Component

{ + render() { + return <>hello; + } + } + let x = ; // should error + let y = ; // should error + + let z = // should work + let q = // should work +} \ No newline at end of file diff --git a/tests/cases/compiler/tsxSpreadDoesNotReportExcessProps.tsx b/tests/cases/compiler/tsxSpreadDoesNotReportExcessProps.tsx new file mode 100644 index 00000000000..3e7e4d1a480 --- /dev/null +++ b/tests/cases/compiler/tsxSpreadDoesNotReportExcessProps.tsx @@ -0,0 +1,13 @@ +// @esModuleInterop: true +// @skipLibCheck: true +// @jsx: react +// @strict: true +/// + +import React from "react"; + +class MyComponent extends React.Component<{dataSource: number[], onClick?: any}, {}> { + render() { + return (

); + } +} diff --git a/tests/cases/compiler/tsxStatelessComponentDefaultProps.tsx b/tests/cases/compiler/tsxStatelessComponentDefaultProps.tsx new file mode 100644 index 00000000000..fcbf58e8873 --- /dev/null +++ b/tests/cases/compiler/tsxStatelessComponentDefaultProps.tsx @@ -0,0 +1,17 @@ +// @jsx: react +// @strict: true +// @esModuleInterop: true +/// + +import React from 'react'; +interface Props { + text: string; +} + +function BackButton(_props: Props) { + return
+} +BackButton.defaultProps = { + text: 'Go Back', +}; +let a = diff --git a/tests/cases/compiler/typeParameterDoesntBlockParameterLookup.ts b/tests/cases/compiler/typeParameterDoesntBlockParameterLookup.ts new file mode 100644 index 00000000000..20db3123690 --- /dev/null +++ b/tests/cases/compiler/typeParameterDoesntBlockParameterLookup.ts @@ -0,0 +1 @@ +declare function f(Bar: any): void \ No newline at end of file diff --git a/tests/cases/compiler/undefinedAssignableToGenericMappedIntersection.ts b/tests/cases/compiler/undefinedAssignableToGenericMappedIntersection.ts new file mode 100644 index 00000000000..2b089164676 --- /dev/null +++ b/tests/cases/compiler/undefinedAssignableToGenericMappedIntersection.ts @@ -0,0 +1,7 @@ +// @strict: true +type Errors = { [P in keyof T]: string | undefined } & {all: string | undefined}; +function foo() { + let obj!: Errors + let x!: keyof T; + obj[x] = undefined; +} diff --git a/tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts b/tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts new file mode 100644 index 00000000000..f8504b3ce22 --- /dev/null +++ b/tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts @@ -0,0 +1,9 @@ +// @strict: true +interface Options { + m(x: number): void; + [key: string]: unknown; +} +declare function f(options: number | Options): void; +f({ + m(x) { }, +}); \ No newline at end of file diff --git a/tests/cases/compiler/unionTypeWithIndexedLiteralType.ts b/tests/cases/compiler/unionTypeWithIndexedLiteralType.ts new file mode 100644 index 00000000000..c594c6d1c9d --- /dev/null +++ b/tests/cases/compiler/unionTypeWithIndexedLiteralType.ts @@ -0,0 +1,4 @@ +interface I { x: number; } +interface Idx { [index: string]: U; } +type U = Idx | I | "lit"; +const u: U = { x: "lit" }; \ No newline at end of file diff --git a/tests/cases/compiler/voidReturnIndexUnionInference.ts b/tests/cases/compiler/voidReturnIndexUnionInference.ts new file mode 100644 index 00000000000..e2dd5ac6c72 --- /dev/null +++ b/tests/cases/compiler/voidReturnIndexUnionInference.ts @@ -0,0 +1,24 @@ +// @strict: true +// repro from https://github.com/Microsoft/TypeScript/issues/25274 +export function safeInvoke( + func: ((arg1: A1) => R) | null | undefined, + arg1: A1 +): R | undefined { + if (func) { + return func(arg1); + } else { + return undefined; + } +} + +interface Props { + onFoo?(value: string): boolean; + onBar?(value: string): void; +} + +function bad

(props: Readonly

) { + safeInvoke(props.onFoo, "blah"); + // ERROR HERE!!! + // Type R in signature of safeInvoke incorrectly inferred as {} instead of void! + safeInvoke(props.onBar, "blah"); +} diff --git a/tests/cases/conformance/async/es2017/asyncMethodWithSuperConflict_es6.ts b/tests/cases/conformance/async/es2017/asyncMethodWithSuperConflict_es6.ts index 364f0264b23..88ed3eea5ff 100644 --- a/tests/cases/conformance/async/es2017/asyncMethodWithSuperConflict_es6.ts +++ b/tests/cases/conformance/async/es2017/asyncMethodWithSuperConflict_es6.ts @@ -2,14 +2,19 @@ class A { x() { } + y() { + } } class B extends A { // async method with only call/get on 'super' does not require a binding async simple() { const _super = null; + const _superIndex = null; // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -24,6 +29,7 @@ class B extends A { // async method with assignment/destructuring on 'super' requires a binding async advanced() { const _super = null; + const _superIndex = null; const f = () => {}; // call with property access @@ -50,4 +56,4 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} \ No newline at end of file +} diff --git a/tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts b/tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts index b9005c48596..892acfd6dd2 100644 --- a/tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts +++ b/tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts @@ -3,6 +3,8 @@ class A { x() { } + y() { + } } class B extends A { @@ -10,6 +12,8 @@ class B extends A { async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -49,4 +53,4 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} \ No newline at end of file +} diff --git a/tests/cases/conformance/async/es5/asyncMethodWithSuper_es5.ts b/tests/cases/conformance/async/es5/asyncMethodWithSuper_es5.ts index 496d8d1c802..c89369d02b7 100644 --- a/tests/cases/conformance/async/es5/asyncMethodWithSuper_es5.ts +++ b/tests/cases/conformance/async/es5/asyncMethodWithSuper_es5.ts @@ -4,6 +4,8 @@ class A { x() { } + y() { + } } class B extends A { @@ -11,6 +13,8 @@ class B extends A { async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -50,4 +54,4 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} \ No newline at end of file +} diff --git a/tests/cases/conformance/async/es6/asyncMethodWithSuper_es6.ts b/tests/cases/conformance/async/es6/asyncMethodWithSuper_es6.ts index 795fe7defb0..79d110e3d85 100644 --- a/tests/cases/conformance/async/es6/asyncMethodWithSuper_es6.ts +++ b/tests/cases/conformance/async/es6/asyncMethodWithSuper_es6.ts @@ -3,6 +3,8 @@ class A { x() { } + y() { + } } class B extends A { @@ -10,6 +12,8 @@ class B extends A { async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -49,4 +53,4 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} \ No newline at end of file +} diff --git a/tests/cases/conformance/controlFlow/controlFlowElementAccess.ts b/tests/cases/conformance/controlFlow/controlFlowElementAccess.ts new file mode 100644 index 00000000000..eb802e3083c --- /dev/null +++ b/tests/cases/conformance/controlFlow/controlFlowElementAccess.ts @@ -0,0 +1,9 @@ +let x: { o: boolean } = { o: false } +if (x['o'] === false) { + x['o'] = true +} + +const y: [number, number] = [0, 0]; +if (y[0] === 0) { + y[0] = -1; +} diff --git a/tests/cases/conformance/controlFlow/controlFlowInstanceOfGuardPrimitives.ts b/tests/cases/conformance/controlFlow/controlFlowInstanceOfGuardPrimitives.ts new file mode 100644 index 00000000000..516c6b62774 --- /dev/null +++ b/tests/cases/conformance/controlFlow/controlFlowInstanceOfGuardPrimitives.ts @@ -0,0 +1,13 @@ +function distinguish(thing: string | number | Date) { + if (thing instanceof Object) { + console.log("Aha!! It's a Date in " + thing.getFullYear()); + } else if (typeof thing === 'string') { + console.log("Aha!! It's a string of length " + thing.length); + } else { + console.log("Aha!! It's the number " + thing.toPrecision(3)); + } +} + +distinguish(new Date()); +distinguish("beef"); +distinguish(3.14159265); \ No newline at end of file diff --git a/tests/cases/conformance/controlFlow/controlFlowInstanceofExtendsFunction.ts b/tests/cases/conformance/controlFlow/controlFlowInstanceofExtendsFunction.ts new file mode 100644 index 00000000000..4a1ff7ff867 --- /dev/null +++ b/tests/cases/conformance/controlFlow/controlFlowInstanceofExtendsFunction.ts @@ -0,0 +1,32 @@ +declare global { + interface Function { + now(): string; + } +} + +Function.prototype.now = function () { + return "now" +} + +class X { + static now() { + return {} + } + + why() { + + } +} + +class Y { + +} + +console.log(X.now()) // works as expected +console.log(Y.now()) // works as expected + +export const x: X | number = Math.random() > 0.5 ? new X() : 1 + +if (x instanceof X) { + x.why() // should compile +} \ No newline at end of file diff --git a/tests/cases/conformance/controlFlow/controlFlowTruthiness.ts b/tests/cases/conformance/controlFlow/controlFlowTruthiness.ts index ba1947da13b..0245f9bfea0 100644 --- a/tests/cases/conformance/controlFlow/controlFlowTruthiness.ts +++ b/tests/cases/conformance/controlFlow/controlFlowTruthiness.ts @@ -68,3 +68,30 @@ function f6() { y; // string | undefined } } + +function f7(x: {}) { + if (x) { + x; // {} + } + else { + x; // {} + } +} + +function f8(x: T) { + if (x) { + x; // {} + } + else { + x; // {} + } +} + +function f9(x: T) { + if (x) { + x; // {} + } + else { + x; // never + } +} \ No newline at end of file diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts new file mode 100644 index 00000000000..b03c1eea078 --- /dev/null +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts @@ -0,0 +1,43 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @declaration: true +// @noImplicitReferences: true +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +// @filename: node_modules/ext/index.d.ts +declare module "ext" { + export interface A {} + export function fa(): A; +} +declare module "ext/other" { + export interface B {} + export function fb(): B; +} +// @filename: node_modules/ext/ts3.1/index.d.ts +declare module "ext" { + export interface A {} + export function fa(): A; +} +declare module "ext/other" { + export interface B {} + export function fb(): B; +} + +// @filename: main.ts +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts new file mode 100644 index 00000000000..01adfac0480 --- /dev/null +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts @@ -0,0 +1,39 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @declaration: true +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +// @filename: node_modules/ext/index.d.ts +export interface A {} +export function fa(): A; + +// @filename: node_modules/ext/other.d.ts +export interface B {} +export function fb(): B; + +// @filename: node_modules/ext/ts3.1/index.d.ts +export interface A {} +export function fa(): A; + +// @filename: node_modules/ext/ts3.1/other.d.ts +export interface B {} +export function fb(): B; + +// @filename: main.ts +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts new file mode 100644 index 00000000000..ee37f436302 --- /dev/null +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts @@ -0,0 +1,37 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @declaration: true +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +// @filename: node_modules/ext/index.d.ts +export interface A {} +export function fa(): A; + +// @filename: node_modules/ext/other.d.ts +export interface B {} +export function fb(): B; + +// @filename: node_modules/ext/ts3.1/index.d.ts +export * from "../"; + +// @filename: node_modules/ext/ts3.1/other.d.ts +export * from "../other"; + +// @filename: main.ts +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts new file mode 100644 index 00000000000..7ef6adcce52 --- /dev/null +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts @@ -0,0 +1,36 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @declaration: true +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "index" : ["ts3.1/index"] + } + } +} + +// @filename: node_modules/ext/index.d.ts +export interface A {} +export function fa(): A; + +// @filename: node_modules/ext/other.d.ts +export interface A2 {} +export function fa(): A2; + +// @filename: node_modules/ext/ts3.1/index.d.ts +export * from "../other"; + +// @filename: main.ts +import { fa } from "ext"; +import { fa as fa2 } from "ext/other"; + +export const va = fa(); +export const va2 = fa2(); + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts b/tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts index e45df9c45df..7ab33f99a1e 100644 --- a/tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts +++ b/tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts @@ -148,36 +148,38 @@ function f19() { var x = ([a, b] = [1, 2]); } -function f20() { +function f20(v: [number, number, number]) { var x: number; var y: number; var z: number; - var a: number[]; - var a3: any[]; - var [...a] = [1, 2, 3]; - var [x, ...a] = [1, 2, 3]; - var [x, y, ...a] = [1, 2, 3]; - var [x, y, z, ...a3] = [1, 2, 3]; - [...a] = [1, 2, 3]; - [x, ...a] = [1, 2, 3]; - [x, y, ...a] = [1, 2, 3]; - [x, y, z, ...a3] = [1, 2, 3]; + var a0: []; + var a1: [number]; + var a2: [number, number]; + var a3: [number, number, number]; + var [...a3] = v; + var [x, ...a2] = v; + var [x, y, ...a1] = v; + var [x, y, z, ...a0] = v; + [...a3] = v; + [x, ...a2] = v; + [x, y, ...a1] = v; + [x, y, z, ...a0] = v; } -function f21() { +function f21(v: [number, string, boolean]) { var x: number; var y: string; var z: boolean; - var a0: (number | string | boolean)[]; - var a1: (string | boolean)[]; - var a2: boolean[]; - var a3: any[]; - var [...a0] = [1, "hello", true]; - var [x, ...a1] = [1, "hello", true]; - var [x, y, ...a2] = [1, "hello", true]; - var [x, y, z, ...a3] = [1, "hello", true]; - [...a0] = [1, "hello", true]; - [x, ...a1] = [1, "hello", true]; - [x, y, ...a2] = [1, "hello", true]; - [x, y, z, ...a3] = [1, "hello", true]; + var a0: [number, string, boolean]; + var a1: [string, boolean]; + var a2: [boolean]; + var a3: []; + var [...a0] = v; + var [x, ...a1] = v; + var [x, y, ...a2] = v; + var [x, y, z, ...a3] = v; + [...a0] = v; + [x, ...a1] = v; + [x, y, ...a2] = v; + [x, y, z, ...a3] = v; } diff --git a/tests/cases/conformance/functions/strictBindCallApply1.ts b/tests/cases/conformance/functions/strictBindCallApply1.ts new file mode 100644 index 00000000000..5a94d4b5416 --- /dev/null +++ b/tests/cases/conformance/functions/strictBindCallApply1.ts @@ -0,0 +1,59 @@ +// @strict: true + +declare function foo(a: number, b: string): string; + +let f00 = foo.bind(undefined); +let f01 = foo.bind(undefined, 10); +let f02 = foo.bind(undefined, 10, "hello"); +let f03 = foo.bind(undefined, 10, 20); // Error + +let c00 = foo.call(undefined, 10, "hello"); +let c01 = foo.call(undefined, 10); // Error +let c02 = foo.call(undefined, 10, 20); // Error +let c03 = foo.call(undefined, 10, "hello", 30); // Error + +let a00 = foo.apply(undefined, [10, "hello"]); +let a01 = foo.apply(undefined, [10]); // Error +let a02 = foo.apply(undefined, [10, 20]); // Error +let a03 = foo.apply(undefined, [10, "hello", 30]); // Error + +class C { + constructor(a: number, b: string) {} + foo(this: this, a: number, b: string): string { return "" } +} + +declare let c: C; +declare let obj: {}; + +let f10 = c.foo.bind(c); +let f11 = c.foo.bind(c, 10); +let f12 = c.foo.bind(c, 10, "hello"); +let f13 = c.foo.bind(c, 10, 20); // Error +let f14 = c.foo.bind(undefined); // Error + +let c10 = c.foo.call(c, 10, "hello"); +let c11 = c.foo.call(c, 10); // Error +let c12 = c.foo.call(c, 10, 20); // Error +let c13 = c.foo.call(c, 10, "hello", 30); // Error +let c14 = c.foo.call(undefined, 10, "hello"); // Error + +let a10 = c.foo.apply(c, [10, "hello"]); +let a11 = c.foo.apply(c, [10]); // Error +let a12 = c.foo.apply(c, [10, 20]); // Error +let a13 = c.foo.apply(c, [10, "hello", 30]); // Error +let a14 = c.foo.apply(undefined, [10, "hello"]); // Error + +let f20 = C.bind(undefined); +let f21 = C.bind(undefined, 10); +let f22 = C.bind(undefined, 10, "hello"); +let f23 = C.bind(undefined, 10, 20); // Error + +C.call(c, 10, "hello"); +C.call(c, 10); // Error +C.call(c, 10, 20); // Error +C.call(c, 10, "hello", 30); // Error + +C.apply(c, [10, "hello"]); +C.apply(c, [10]); // Error +C.apply(c, [10, 20]); // Error +C.apply(c, [10, "hello", 30]); // Error diff --git a/tests/cases/conformance/jsdoc/constructorTagOnClassConstructor.ts b/tests/cases/conformance/jsdoc/constructorTagOnClassConstructor.ts new file mode 100644 index 00000000000..6d2f3780eee --- /dev/null +++ b/tests/cases/conformance/jsdoc/constructorTagOnClassConstructor.ts @@ -0,0 +1,14 @@ +// @allowJs: true +// @noEmit: true +// @checkJs: true +// @Filename: bug27025.js +export class Alpha { } +export class Beta { + /** + * @constructor + */ + constructor() { + } +} + +const arr = [Alpha, Beta]; diff --git a/tests/cases/conformance/jsdoc/constructorTagOnObjectLiteralMethod.ts b/tests/cases/conformance/jsdoc/constructorTagOnObjectLiteralMethod.ts new file mode 100644 index 00000000000..d73ba6766c5 --- /dev/null +++ b/tests/cases/conformance/jsdoc/constructorTagOnObjectLiteralMethod.ts @@ -0,0 +1,10 @@ +// @noEmit: true +// @Filename: example.js +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +const obj = { + /** @constructor */ + Foo() { this.bar = "bar" } +}; +(new obj.Foo()).bar diff --git a/tests/cases/conformance/jsdoc/enumTag.ts b/tests/cases/conformance/jsdoc/enumTag.ts index bd740d879a1..a857d4eccce 100644 --- a/tests/cases/conformance/jsdoc/enumTag.ts +++ b/tests/cases/conformance/jsdoc/enumTag.ts @@ -11,7 +11,7 @@ const Target = { /** @type {number} */ OK_I_GUESS: 2 } -/** @enum {number} */ +/** @enum number */ const Second = { MISTAKE: "end", OK: 1, diff --git a/tests/cases/conformance/jsdoc/enumTagCircularReference.ts b/tests/cases/conformance/jsdoc/enumTagCircularReference.ts new file mode 100644 index 00000000000..c4015b70985 --- /dev/null +++ b/tests/cases/conformance/jsdoc/enumTagCircularReference.ts @@ -0,0 +1,7 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @Filename: bug27142.js + +/** @enum {E} */ +const E = { x: 0 }; diff --git a/tests/cases/conformance/jsdoc/enumTagUseBeforeDefCrash.ts b/tests/cases/conformance/jsdoc/enumTagUseBeforeDefCrash.ts new file mode 100644 index 00000000000..f8f92b7bcc1 --- /dev/null +++ b/tests/cases/conformance/jsdoc/enumTagUseBeforeDefCrash.ts @@ -0,0 +1,13 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @Filename: bug27134.js +/** + * @enum {number} + */ +var foo = { }; + +/** + * @type {foo} + */ +var s; diff --git a/tests/cases/conformance/jsdoc/jsdocBindingInUnreachableCode.ts b/tests/cases/conformance/jsdoc/jsdocBindingInUnreachableCode.ts new file mode 100644 index 00000000000..2c4accf993b --- /dev/null +++ b/tests/cases/conformance/jsdoc/jsdocBindingInUnreachableCode.ts @@ -0,0 +1,11 @@ +// @allowJs: true +// @noEmit: true +// @checkJs: true +// @Filename: bug27341.js +if (false) { + /** + * @param {string} s + */ + const x = function (s) { + }; +} diff --git a/tests/cases/conformance/jsdoc/jsdocTypeReferenceExports.ts b/tests/cases/conformance/jsdoc/jsdocTypeReferenceExports.ts new file mode 100644 index 00000000000..e711ad4f58f --- /dev/null +++ b/tests/cases/conformance/jsdoc/jsdocTypeReferenceExports.ts @@ -0,0 +1,10 @@ +// @allowJs: true +// @noEmit: true +// @checkJs: true +// @Filename: bug27342.js +module.exports = {} +/** + * @type {exports} + */ +var x + diff --git a/tests/cases/conformance/jsdoc/typeTagCircularReferenceOnConstructorFunction.ts b/tests/cases/conformance/jsdoc/typeTagCircularReferenceOnConstructorFunction.ts new file mode 100644 index 00000000000..9d511ed4375 --- /dev/null +++ b/tests/cases/conformance/jsdoc/typeTagCircularReferenceOnConstructorFunction.ts @@ -0,0 +1,9 @@ +// @allowJs: true +// @noEmit: true +// @checkJs: true +// @Filename: bug27346.js +/** + * @type {MyClass} + */ +function MyClass() { } +MyClass.prototype = {}; diff --git a/tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx b/tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx new file mode 100644 index 00000000000..646bfebca5e --- /dev/null +++ b/tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx @@ -0,0 +1,24 @@ +// @jsx: react +// @strict: true +// @esModuleInterop: true +/// + +import React from 'react' + +interface ResizablePanelProps { + children: [React.ReactNode, React.ReactNode] +} + +class ResizablePanel extends React.Component< + ResizablePanelProps, any> {} + +const test = +

+
+ + +const testErr = +
+
+
+ \ No newline at end of file diff --git a/tests/cases/conformance/jsx/checkJsxUnionSFXContextualTypeInferredCorrectly.tsx b/tests/cases/conformance/jsx/checkJsxUnionSFXContextualTypeInferredCorrectly.tsx new file mode 100644 index 00000000000..7d4f6071e81 --- /dev/null +++ b/tests/cases/conformance/jsx/checkJsxUnionSFXContextualTypeInferredCorrectly.tsx @@ -0,0 +1,40 @@ +// @jsx: react +// @strict: true +// @esModuleInterop: true +/// + +import React from 'react'; + +interface PS { + multi: false + value: string | undefined + onChange: (selection: string | undefined) => void +} + +interface PM { + multi: true + value: string[] + onChange: (selection: string[]) => void +} + +export function ComponentWithUnion(props: PM | PS) { + return

; +} + +// Usage with React tsx +export function HereIsTheError() { + return ( + console.log(val)} // <- this throws an error + /> + ); +} + +// Usage with pure TypeScript +ComponentWithUnion({ + multi: false, + value: 's', + onChange: val => console.log(val) // <- this works fine +}); diff --git a/tests/cases/conformance/jsx/tsxAttributeResolution15.tsx b/tests/cases/conformance/jsx/tsxAttributeResolution15.tsx index 01dedf4711e..92bb9f50e7c 100644 --- a/tests/cases/conformance/jsx/tsxAttributeResolution15.tsx +++ b/tests/cases/conformance/jsx/tsxAttributeResolution15.tsx @@ -2,6 +2,7 @@ // @jsx: preserve // @noLib: true // @skipLibCheck: true +// @noImplicitAny: true // @libFiles: react.d.ts,lib.d.ts import React = require('react'); diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx index f32b367b718..ad8461bc1a7 100644 --- a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx @@ -19,6 +19,9 @@ class Poisoned extends React.Component { const obj = {}; +// OK +; + // Error let p = ; let y = ; diff --git a/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts b/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts new file mode 100644 index 00000000000..870a1a1308d --- /dev/null +++ b/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts @@ -0,0 +1,39 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @noImplicitReferences: true +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +// @filename: node_modules/ext/index.d.ts +declare module "ext" { + export const a = "default a"; +} +declare module "ext/other" { + export const b = "default b"; +} + +// @filename: node_modules/ext/ts3.1/index.d.ts +declare module "ext" { + export const a = "ts3.1 a"; +} +declare module "ext/other" { + export const b = "ts3.1 b"; +} + +// @filename: main.ts +import { a } from "ext"; +import { b } from "ext/other"; + +const aa: "ts3.1 a" = a; +const bb: "ts3.1 b" = b; + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/moduleResolution/typesVersions.justIndex.ts b/tests/cases/conformance/moduleResolution/typesVersions.justIndex.ts new file mode 100644 index 00000000000..966a0a54153 --- /dev/null +++ b/tests/cases/conformance/moduleResolution/typesVersions.justIndex.ts @@ -0,0 +1,17 @@ +// @baseUrl: / +// @traceResolution: true +// @target: esnext +// @module: commonjs + +// @filename: /a/package.json +{ + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +// @filename: /a/ts3.1/index.d.ts +export const a = 0; + +// @filename: /b/user.ts +import { a } from "a"; diff --git a/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts b/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts new file mode 100644 index 00000000000..14a05118b65 --- /dev/null +++ b/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts @@ -0,0 +1,34 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*" : ["ts3.1/*"] } + } +} + +// @filename: node_modules/ext/index.d.ts +export const a = "default a"; + +// @filename: node_modules/ext/other.d.ts +export const b = "default b"; + +// @filename: node_modules/ext/ts3.1/index.d.ts +export const a = "ts3.1 a"; + +// @filename: node_modules/ext/ts3.1/other.d.ts +export const b = "ts3.1 b"; + +// @filename: main.ts +import { a } from "ext"; +import { b } from "ext/other"; + +const aa: "ts3.1 a" = a; +const bb: "ts3.1 b" = b; + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/salsa/classCanExtendConstructorFunction.ts b/tests/cases/conformance/salsa/classCanExtendConstructorFunction.ts index 6946507c80e..89536584643 100644 --- a/tests/cases/conformance/salsa/classCanExtendConstructorFunction.ts +++ b/tests/cases/conformance/salsa/classCanExtendConstructorFunction.ts @@ -99,6 +99,8 @@ class Chowder extends Soup { var soup = new Soup(1); soup.flavour -var chowder = new Chowder(); +var chowder = new Chowder({ claim: "ignorant" }); chowder.flavour.claim +var errorNoArgs = new Chowder(); +var errorArgType = new Chowder(0); diff --git a/tests/cases/conformance/salsa/constructorFunctionMergeWithClass.ts b/tests/cases/conformance/salsa/constructorFunctionMergeWithClass.ts new file mode 100644 index 00000000000..b6a0a50f029 --- /dev/null +++ b/tests/cases/conformance/salsa/constructorFunctionMergeWithClass.ts @@ -0,0 +1,14 @@ +// @allowJs: true +// @noEmit: true +// @checkJs: true + +// @Filename: file1.js +var SomeClass = function () { + this.otherProp = 0; +}; + +new SomeClass(); + +// @Filename: file2.js +class SomeClass { } +SomeClass.prop = 0 diff --git a/tests/cases/conformance/salsa/constructorFunctions.ts b/tests/cases/conformance/salsa/constructorFunctions.ts index 97486bb988c..35eae4b0e28 100644 --- a/tests/cases/conformance/salsa/constructorFunctions.ts +++ b/tests/cases/conformance/salsa/constructorFunctions.ts @@ -24,7 +24,7 @@ function C3() { if (!(this instanceof C3)) return new C3(); }; -const c3_v1 = C3(); +const c3_v1 = C3(); // error: @class tag requires 'new' const c3_v2 = new C3(); /** @class */ @@ -32,7 +32,7 @@ var C4 = function () { if (!(this instanceof C4)) return new C4(); }; -const c4_v1 = C4(); +const c4_v1 = C4(); // error: @class tag requires 'new' const c4_v2 = new C4(); var c5_v1; diff --git a/tests/cases/conformance/salsa/globalMergeWithCommonJSAssignmentDeclaration.ts b/tests/cases/conformance/salsa/globalMergeWithCommonJSAssignmentDeclaration.ts new file mode 100644 index 00000000000..f1435eea87e --- /dev/null +++ b/tests/cases/conformance/salsa/globalMergeWithCommonJSAssignmentDeclaration.ts @@ -0,0 +1,8 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @Filename: bug27099.js +window.name = 1; +window.console; // should not have error: Property 'console' does not exist on type 'typeof window'. +module.exports = 'anything'; + diff --git a/tests/cases/conformance/salsa/moduleExportAliasUnknown.ts b/tests/cases/conformance/salsa/moduleExportAliasUnknown.ts new file mode 100644 index 00000000000..f2fdb384e61 --- /dev/null +++ b/tests/cases/conformance/salsa/moduleExportAliasUnknown.ts @@ -0,0 +1,6 @@ +// @allowJs: true +// @noEmit: true +// @checkJs: true +// @Filename: bug27025.js +module.exports = window.nonprop; +exports.foo = bar; diff --git a/tests/cases/conformance/salsa/typeFromPropertyAssignment35.ts b/tests/cases/conformance/salsa/typeFromPropertyAssignment35.ts new file mode 100644 index 00000000000..952fdd7c9c0 --- /dev/null +++ b/tests/cases/conformance/salsa/typeFromPropertyAssignment35.ts @@ -0,0 +1,22 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true + +// @Filename: bug26877.js +/** @param {Emu.D} x */ +function ollKorrect(x) { + x._model + const y = new Emu.D() + const z = Emu.D._wrapperInstance; +} +Emu.D = class { + constructor() { + this._model = 1 + } +} + +// @Filename: second.js +var Emu = {} +/** @type {string} */ +Emu.D._wrapperInstance; + diff --git a/tests/cases/conformance/salsa/typeFromPropertyAssignment36.ts b/tests/cases/conformance/salsa/typeFromPropertyAssignment36.ts new file mode 100644 index 00000000000..ee1038f48ca --- /dev/null +++ b/tests/cases/conformance/salsa/typeFromPropertyAssignment36.ts @@ -0,0 +1,73 @@ +// @strict: true +function f(b: boolean) { + function d() { + } + d.e = 12 + d.e + + if (b) { + d.q = false + } + // error d.q might not be assigned + d.q + if (b) { + d.q = false + } + else { + d.q = true + } + d.q + if (b) { + d.r = 1 + } + else { + d.r = 2 + } + d.r + if (b) { + d.s = 'hi' + } + return d +} +// OK to access possibly-unassigned properties outside the initialising scope +var test = f(true).s + +function d() { +} +d.e = 12 +d.e + +if (!!false) { + d.q = false +} +d.q +if (!!false) { + d.q = false +} +else { + d.q = true +} +d.q +if (!!false) { + d.r = 1 +} +else { + d.r = 2 +} +d.r + +// test function expressions too +const g = function() { +} +if (!!false) { + g.expando = 1 +} +g.expando // error + +if (!!false) { + g.both = 'hi' +} +else { + g.both = 0 +} +g.both diff --git a/tests/cases/conformance/salsa/typeFromPropertyAssignment37.ts b/tests/cases/conformance/salsa/typeFromPropertyAssignment37.ts new file mode 100644 index 00000000000..0e60c78621e --- /dev/null +++ b/tests/cases/conformance/salsa/typeFromPropertyAssignment37.ts @@ -0,0 +1,15 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @Filename: mod.js +const util = exports = module.exports = {} +if (!!false) { + util.existy = function () { } +} + +// @Filename: use.js +const util = require('./mod') +function n() { + util.existy // no error +} +util.existy // no error diff --git a/tests/cases/conformance/salsa/typeFromPrototypeAssignment.ts b/tests/cases/conformance/salsa/typeFromPrototypeAssignment.ts new file mode 100644 index 00000000000..373ccab0394 --- /dev/null +++ b/tests/cases/conformance/salsa/typeFromPrototypeAssignment.ts @@ -0,0 +1,44 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @Filename: a.js +// @strict: true + +// all references to _map, set, get, addon should be ok + +/** @constructor */ +var Multimap = function() { + this._map = {}; + this._map + this.set + this.get + this.addon +}; + +Multimap.prototype = { + set: function() { + this._map + this.set + this.get + this.addon + }, + get() { + this._map + this.set + this.get + this.addon + } +} + +Multimap.prototype.addon = function () { + this._map + this.set + this.get + this.addon +} + +var mm = new Multimap(); +mm._map +mm.set +mm.get +mm.addon diff --git a/tests/cases/conformance/salsa/typeFromPrototypeAssignment2.ts b/tests/cases/conformance/salsa/typeFromPrototypeAssignment2.ts new file mode 100644 index 00000000000..68966c923d5 --- /dev/null +++ b/tests/cases/conformance/salsa/typeFromPrototypeAssignment2.ts @@ -0,0 +1,46 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @Filename: a.js +// @strict: true + +// non top-level: +// all references to _map, set, get, addon should be ok +(function container() { + /** @constructor */ + var Multimap = function() { + this._map = {}; + this._map + this.set + this.get + this.addon + }; + + Multimap.prototype = { + set: function() { + this._map + this.set + this.get + this.addon + }, + get() { + this._map + this.set + this.get + this.addon + } + } + + Multimap.prototype.addon = function () { + this._map + this.set + this.get + this.addon + } + + var mm = new Multimap(); + mm._map + mm.set + mm.get + mm.addon +}); diff --git a/tests/cases/conformance/types/contextualTypes/asyncFunctions/contextuallyTypeAsyncFunctionAwaitOperand.ts b/tests/cases/conformance/types/contextualTypes/asyncFunctions/contextuallyTypeAsyncFunctionAwaitOperand.ts new file mode 100644 index 00000000000..81ef725a45b --- /dev/null +++ b/tests/cases/conformance/types/contextualTypes/asyncFunctions/contextuallyTypeAsyncFunctionAwaitOperand.ts @@ -0,0 +1,11 @@ +// @target: esnext +// @noImplicitAny: true +// @noEmit: true + +interface Obj { key: "value"; } + +async function fn1(): Promise { + const obj1: Obj = await { key: "value" }; + const obj2: Obj = await new Promise(resolve => resolve({ key: "value" })); + return await { key: "value" }; +} diff --git a/tests/cases/conformance/types/contextualTypes/asyncFunctions/contextuallyTypeAsyncFunctionReturnType.ts b/tests/cases/conformance/types/contextualTypes/asyncFunctions/contextuallyTypeAsyncFunctionReturnType.ts new file mode 100644 index 00000000000..b2239b9bda6 --- /dev/null +++ b/tests/cases/conformance/types/contextualTypes/asyncFunctions/contextuallyTypeAsyncFunctionReturnType.ts @@ -0,0 +1,25 @@ +// @target: esnext +// @noImplicitAny: true +// @noEmit: true + +interface Obj { key: "value"; } + +async function fn1(): Promise { + return { key: "value" }; +} + +async function fn2(): Promise { + return new Promise(resolve => { + resolve({ key: "value" }); + }); +} + +async function fn3(): Promise { + return await { key: "value" }; +} + +async function fn4(): Promise { + return await new Promise(resolve => { + resolve({ key: "value" }); + }); +} \ No newline at end of file diff --git a/tests/cases/conformance/types/forAwait/types.forAwait.esnext.1.ts b/tests/cases/conformance/types/forAwait/types.forAwait.esnext.1.ts index 4537e09a048..8b5157250b8 100644 --- a/tests/cases/conformance/types/forAwait/types.forAwait.esnext.1.ts +++ b/tests/cases/conformance/types/forAwait/types.forAwait.esnext.1.ts @@ -3,16 +3,21 @@ // @noEmit: true declare const asyncIterable: AsyncIterable; declare const iterable: Iterable; +declare const iterableOfPromise: Iterable>; async function f1() { let y: number; for await (const x of asyncIterable) { } for await (const x of iterable) { } + for await (const x of iterableOfPromise) { + } for await (y of asyncIterable) { } for await (y of iterable) { } + for await (y of iterableOfPromise) { + } } async function * f2() { let y: number; @@ -20,8 +25,12 @@ async function * f2() { } for await (const x of iterable) { } + for await (const x of iterableOfPromise) { + } for await (y of asyncIterable) { } for await (y of iterable) { } + for await (y of iterableOfPromise) { + } } \ No newline at end of file diff --git a/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts b/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts index 7748240f80d..cf05bdfed81 100644 --- a/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts +++ b/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts @@ -63,12 +63,11 @@ type Q21 = Shape[WIDTH_OR_HEIGHT]; // number type Q30 = [string, number][0]; // string type Q31 = [string, number][1]; // number -type Q32 = [string, number][2]; // string | number +type Q32 = [string, number][number]; // string | number type Q33 = [string, number][E.A]; // string type Q34 = [string, number][E.B]; // number -type Q35 = [string, number][E.C]; // string | number -type Q36 = [string, number]["0"]; // string -type Q37 = [string, number]["1"]; // string +type Q35 = [string, number]["0"]; // string +type Q36 = [string, number]["1"]; // string type Q40 = (Shape | Options)["visible"]; // boolean | "yes" | "no" type Q41 = (Shape & Options)["visible"]; // true & "yes" | true & "no" | false & "yes" | false & "no" @@ -302,23 +301,16 @@ type S2 = { b: string; }; -function f90(x1: S2[keyof S2], x2: T[keyof S2], x3: S2[K], x4: T[K]) { +function f90(x1: S2[keyof S2], x2: T[keyof S2], x3: S2[K]) { x1 = x2; x1 = x3; - x1 = x4; x2 = x1; x2 = x3; - x2 = x4; x3 = x1; x3 = x2; - x3 = x4; - x4 = x1; - x4 = x2; - x4 = x3; x1.length; x2.length; x3.length; - x4.length; } function f91(x: T, y: T[keyof T], z: T[K]) { diff --git a/tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts b/tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts index bb2b9d95117..a4ed608d8e7 100644 --- a/tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts +++ b/tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts @@ -116,3 +116,28 @@ function f3, U extends T, J extends K>( tk = uj; uj = tk; // error } + +// The constraint of 'keyof T' is 'keyof T' +function f4(k: keyof T) { + k = 42; // error + k = "hello"; // error +} + +// Repro from #27470 + +type UndefinedKeys> = { + [K in keyof T]: undefined extends T[K] ? K : never +}; + +type MyType = {a: string, b: string | undefined} + +type Result1 = UndefinedKeys; + +const a1: Result1['a'] = 'a'; // Error +const b1: Result1['b'] = 'b'; + +function test1, K extends keyof T>(t: T, k: K) { + t[k] = 42; // Error + t[k] = "hello"; // Error + t[k] = [10, 20]; // Error +} diff --git a/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts b/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts index 7a78ad9dc4a..188efa2f51a 100644 --- a/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts +++ b/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts @@ -12,4 +12,13 @@ type Recurse1 = { type Recurse2 = { [K in keyof Recurse1]: Recurse1[K] -} \ No newline at end of file +} + +// Repro from #27881 + +export type Circular = {[P in keyof T]: Circular}; +type tup = [number, number, number, number]; + +function foo(arg: Circular): tup { + return arg; +} diff --git a/tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts b/tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts new file mode 100644 index 00000000000..9eae78919a4 --- /dev/null +++ b/tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts @@ -0,0 +1,64 @@ +// @strict: true + +type T1 = [string, number]; +type T2 = [boolean] | [string, number]; +type T3 = [string, ...number[]]; +type T4 = [boolean] | [string, ...number[]]; + +type T10 = T1[0]; // string +type T11 = T1[1]; // number +type T12 = T1[2]; // undefined +type T1N = T1[number]; // string | number + +type T20 = T2[0]; // string | boolean +type T21 = T2[1]; // number | undefined +type T22 = T2[2]; // undefined +type T2N = T2[number]; // string | number | boolean + +type T30 = T3[0]; // string +type T31 = T3[1]; // number +type T32 = T3[2]; // number +type T3N = T3[number]; // string | number + +type T40 = T4[0]; // string | boolean +type T41 = T4[1]; // number | undefined +type T42 = T4[2]; // number | undefined +type T4N = T4[number]; // string | number | boolean + +function f1(t1: T1, t2: T2, t3: T3, t4: T4, x: number) { + let [d10, d11, d12] = t1; // string, number + let [d20, d21, d22] = t2; // string | boolean, number | undefined + let [d30, d31, d32] = t3; // string, number, number + let [d40, d41, d42] = t4; // string | boolean, number | undefined, number | undefined + [d10, d11, d12] = t1; + [d20, d21, d22] = t2; + [d30, d31, d32] = t3; + [d40, d41, d42] = t4; + let t10 = t1[0]; // string + let t11 = t1[1]; // number + let t12 = t1[2]; // undefined + let t1x = t1[x]; // string | number + let t20 = t2[0]; // string | boolean + let t21 = t2[1]; // number | undefined + let t22 = t2[2]; // undefined + let t2x = t2[x]; // string | number | boolean + let t30 = t3[0]; // string + let t31 = t3[1]; // number + let t32 = t3[2]; // number + let t3x = t3[x]; // string | number + let t40 = t4[0]; // string | boolean + let t41 = t4[1]; // number | undefined + let t42 = t4[2]; // number | undefined + let t4x = t4[x]; // string | number | boolean + t1[1] = 42; + t2[1] = 42; + t3[1] = 42; + t4[1] = 42; +} + +// Repro from #27543 + +type Unioned = [string] | [string, number]; +const ex: Unioned = ["hi"] as Unioned; + +const [x, y] = ex; diff --git a/tests/cases/conformance/types/typeRelationships/typeInference/bivariantInferences.ts b/tests/cases/conformance/types/typeRelationships/typeInference/bivariantInferences.ts new file mode 100644 index 00000000000..c0e2ee497d0 --- /dev/null +++ b/tests/cases/conformance/types/typeRelationships/typeInference/bivariantInferences.ts @@ -0,0 +1,12 @@ +// @strict: true + +// Repro from #27337 + +interface Array { + equalsShallow(this: ReadonlyArray, other: ReadonlyArray): boolean; +} + +declare const a: (string | number)[] | null[] | undefined[] | {}[]; +declare const b: (string | number)[] | null[] | undefined[] | {}[]; + +let x = a.equalsShallow(b); diff --git a/tests/cases/conformance/types/union/contextualTypeWithUnionTypeIndexSignatures.ts b/tests/cases/conformance/types/union/contextualTypeWithUnionTypeIndexSignatures.ts index 9132c61f4fe..a7408672118 100644 --- a/tests/cases/conformance/types/union/contextualTypeWithUnionTypeIndexSignatures.ts +++ b/tests/cases/conformance/types/union/contextualTypeWithUnionTypeIndexSignatures.ts @@ -38,7 +38,7 @@ interface IWithNumberIndexSignature2 { // If S is not empty, U has a string index signature of a union type of // the types of the string index signatures from each type in S. var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { z: a => a }; // a should be number -var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: a => a }; // a should be any +var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: a => a }; // a should be number (because of index signature of IWithStringIndexSignature1) var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: "hello" }; var x2: IWithStringIndexSignature1 | IWithStringIndexSignature2 = { z: a => a.toString() }; // a should be number var x2: IWithStringIndexSignature1 | IWithStringIndexSignature2 = { z: a => a }; // a should be number @@ -48,7 +48,7 @@ var x2: IWithStringIndexSignature1 | IWithStringIndexSignature2 = { z: a => a }; // If S is not empty, U has a numeric index signature of a union type of // the types of the numeric index signatures from each type in S. var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 1: a => a }; // a should be number -var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: a => a }; // a should be any +var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: a => a }; // a should be number (because of index signature of IWithNumberIndexSignature1) var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: "hello" }; var x4: IWithNumberIndexSignature1 | IWithNumberIndexSignature2 = { 1: a => a.toString() }; // a should be number var x4: IWithNumberIndexSignature1 | IWithNumberIndexSignature2 = { 1: a => a }; // a should be number \ No newline at end of file diff --git a/tests/cases/conformance/types/union/discriminatedUnionTypes2.ts b/tests/cases/conformance/types/union/discriminatedUnionTypes2.ts new file mode 100644 index 00000000000..789bc263c7e --- /dev/null +++ b/tests/cases/conformance/types/union/discriminatedUnionTypes2.ts @@ -0,0 +1,74 @@ +// @strict: true + +function f10(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { + if (x.kind === false) { + x.a; + } + else if (x.kind === true) { + x.b; + } + else { + x.c; + } +} + +function f11(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { + switch (x.kind) { + case false: + x.a; + break; + case true: + x.b; + break; + default: + x.c; + } +} + +function f13(x: { a: null; b: string } | { a: string, c: number }) { + x = { a: null, b: "foo", c: 4}; // Error +} + +function f14(x: { a: 0; b: string } | { a: T, c: number }) { + if (x.a === 0) { + x.b; // Error + } +} + +type Result = { error?: undefined, value: T } | { error: Error }; + +function f15(x: Result) { + if (!x.error) { + x.value; + } + else { + x.error.message; + } +} + +f15({ value: 10 }); +f15({ error: new Error("boom") }); + +// Repro from #24193 + +interface WithError { + error: Error + data: null +} + +interface WithoutError { + error: null + data: Data +} + +type DataCarrier = WithError | WithoutError + +function f20(carrier: DataCarrier) { + if (carrier.error === null) { + const error: null = carrier.error + const data: Data = carrier.data + } else { + const error: Error = carrier.error + const data: null = carrier.data + } +} diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts index ef626fd358d..5e18925fdfe 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts @@ -4,10 +4,9 @@ /////** @type {number} */ ////var [|x|]; -verify.getSuggestionDiagnostics([{ - message: "JSDoc types may be moved to TypeScript types.", - code: 80004, -}]); +verify.getSuggestionDiagnostics([ + { message: "JSDoc types may be moved to TypeScript types.", code: 80004 }, + { message: "Variable 'x' implicitly has an 'any' type.", code: 7005 }]); verify.codeFix({ description: "Annotate with type from JSDoc", diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts index c5013b80cf1..7e064f8dae4 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts @@ -6,14 +6,17 @@ //// * @param alpha - the other best parameter //// * @param {*} beta - I have no idea how this got here //// */ -////function [|f|](x, y, z: string, alpha, beta) { +////function [|f|]([|x|], [|y|], z: string, [|alpha|], [|beta|]) { //// x; y; z; alpha; beta; ////} -verify.getSuggestionDiagnostics([{ - message: "JSDoc types may be moved to TypeScript types.", - code: 80004, -}]); +const [r0, r1, r2, r3, r4] = test.ranges(); +verify.getSuggestionDiagnostics([ + {message: "JSDoc types may be moved to TypeScript types.", code: 80004, range: r0}, + {message: "Parameter 'x' implicitly has an 'any' type.", code: 7006, range: r1 }, + {message: "Parameter 'y' implicitly has an 'any' type.", code: 7006, range: r2 }, + {message: "Parameter 'alpha' implicitly has an 'any' type.", code: 7006, range: r3 }, + {message: "Parameter 'beta' implicitly has an 'any' type.", code: 7006, range: r4 }]); verify.codeFix({ description: "Annotate with type from JSDoc", diff --git a/tests/cases/fourslash/codeFixCannotFindModule_all.ts b/tests/cases/fourslash/codeFixCannotFindModule_all.ts index 044d0c5deb0..1b1b36d13ad 100644 --- a/tests/cases/fourslash/codeFixCannotFindModule_all.ts +++ b/tests/cases/fourslash/codeFixCannotFindModule_all.ts @@ -21,12 +21,11 @@ test.setTypesRegistry({ goTo.marker(); verify.codeFixAll({ - fixId: "fixCannotFindModule", + fixId: "installTypesPackage", fixAllDescription: "Install all missing types packages", + newFileContent: {}, // no changes commands: [ { packageName: "@types/abs", file: "/a.ts", type: "install package" }, { packageName: "@types/zap", file: "/a.ts", type: "install package" }, ], - newFileContent: `import * as abs from "abs"; -import * as zap from "zap";` // unchanged }); diff --git a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes.ts b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes.ts new file mode 100644 index 00000000000..af8707a9f81 --- /dev/null +++ b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes.ts @@ -0,0 +1,44 @@ +/// + +// @Filename: /dir/node_modules/plus/index.js +////module.exports = function plus(x, y) { return x + y; }; + +// @Filename: /dir/a.ts +////import plus = require("plus"); +////plus; + +// @Filename: /dir/tsconfig.json +////{ +//// "compilerOptions": { +//// "paths": { +//// "nota": ["valid_pathmapping"], +//// dontCrash: 37, +//// "*": ["abc123"], +//// } +//// } +////} + +goTo.file("/dir/a.ts"); +verify.codeFix({ + description: "Generate types for 'plus'", + newFileContent: { + "/dir/tsconfig.json": +`{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "*": ["types/*"], + "nota": ["valid_pathmapping"], + dontCrash: 37, + "*": ["abc123"], + } + } +}`, + }, + commands: [{ + type: "generate types", + file: "/dir/a.ts", + fileToGenerateTypesFor: "/dir/node_modules/plus/index.js", + outputFileName: "/dir/types/plus.d.ts", + }], +}); diff --git a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_all.ts b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_all.ts new file mode 100644 index 00000000000..183ca3324a4 --- /dev/null +++ b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_all.ts @@ -0,0 +1,47 @@ +/// + +// @Filename: /dir/node_modules/plus/index.js +////module.exports = function plus(x, y) { return x + y; }; + +// @Filename: /dir/node_modules/times/index.js +////module.exports = function times(x, y) { return x * y; }; + +// @Filename: /dir/a.ts +////import plus = require("plus"); +////import times = require("times"); +////plus; + +// @Filename: /dir/tsconfig.json +////{ +//// "compilerOptions": {} +////} + +goTo.file("/dir/a.ts"); +verify.codeFixAll({ + fixAllDescription: "Generate types for all packages without types", + fixId: "generateTypes", + newFileContent: { + "/dir/tsconfig.json": +// TODO: GH#26618 +`{ + "compilerOptions": { + "baseUrl": ".", + "paths": { "*": ["types/*"] }, +} +}`, + }, + commands: [ + { + type: "generate types", + file: "/dir/a.ts", + fileToGenerateTypesFor: "/dir/node_modules/plus/index.js", + outputFileName: "/dir/types/plus.d.ts", + }, + { + type: "generate types", + file: "/dir/a.ts", + fileToGenerateTypesFor: "/dir/node_modules/times/index.js", + outputFileName: "/dir/types/times.d.ts", + }, + ], +}); diff --git a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_noExistingCompilerOptions.ts b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_noExistingCompilerOptions.ts new file mode 100644 index 00000000000..99a22078143 --- /dev/null +++ b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_noExistingCompilerOptions.ts @@ -0,0 +1,28 @@ +/// + +// @Filename: /dir/node_modules/plus/index.js +////module.exports = function plus(x, y) { return x * y; }; + +// @Filename: /dir/a.ts +////import plus = require("plus"); +////plus; + +// @Filename: /dir/tsconfig.json +////{} + +goTo.file("/dir/a.ts"); +verify.codeFix({ + description: "Generate types for 'plus'", + newFileContent: { + "/dir/tsconfig.json": +`{ + "compilerOptions": { "baseUrl": ".", "paths": { "*": ["types/*"] } }, +}`, + }, + commands: [{ + type: "generate types", + file: "/dir/a.ts", + fileToGenerateTypesFor: "/dir/node_modules/plus/index.js", + outputFileName: "/dir/types/plus.d.ts", + }], +}); diff --git a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_notForNonexistentPackage.ts b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_notForNonexistentPackage.ts new file mode 100644 index 00000000000..a4e6450e933 --- /dev/null +++ b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_notForNonexistentPackage.ts @@ -0,0 +1,13 @@ +/// + +// @Filename: /a.ts +////import plus = require("plus"); +////plus; + +// @Filename: /tsconfig.json +////{ +//// "compilerOptions": {} +////} + +goTo.file("/a.ts"); +verify.codeFixAvailable([]); diff --git a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_typesDirectoryExists.ts b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_typesDirectoryExists.ts new file mode 100644 index 00000000000..5c095f84ba7 --- /dev/null +++ b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_typesDirectoryExists.ts @@ -0,0 +1,30 @@ +/// + +// @Filename: /dir/node_modules/plus/index.js +////module.exports = function plus(x, y) { return x * y; }; + +// @Filename: /dir/a.ts +////import plus = require("plus"); +////plus; + +// @Filename: /dir/tsconfig.json +////{ +//// "compilerOptions": { +//// "baseUrl": "base", +//// "paths": { +//// "*": ["myTypes/*"], +//// }, +//// }, +////} + +goTo.file("/dir/a.ts"); +verify.codeFix({ + description: "Generate types for 'plus'", + newFileContent: {}, // no change + commands: [{ + type: "generate types", + file: "/dir/a.ts", + fileToGenerateTypesFor: "/dir/node_modules/plus/index.js", + outputFileName: "/dir/base/myTypes/plus.d.ts", + }], +}); diff --git a/tests/cases/fourslash/codeFixGenerateDefinitions.ts b/tests/cases/fourslash/codeFixGenerateDefinitions.ts new file mode 100644 index 00000000000..41dc24d3a3c --- /dev/null +++ b/tests/cases/fourslash/codeFixGenerateDefinitions.ts @@ -0,0 +1,9 @@ +/// + +// @Filename: /node_modules/foo/index.d.ts +////module.exports = 0; + +// @Filename: /a.ts +////import * as foo from "foo"; + +verify.not.codeFixAvailable(); diff --git a/tests/cases/fourslash/codeFixInferFromUsageCallJS.ts b/tests/cases/fourslash/codeFixInferFromUsageCallJS.ts new file mode 100644 index 00000000000..fa7eb5ee671 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageCallJS.ts @@ -0,0 +1,20 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: test.js +////function wat(b) { +//// b(); +////} + +verify.codeFixAll({ + fixId: "inferFromUsage", + fixAllDescription: "Infer all types from usage", + newFileContent: +`/** + * @param {() => void} b + */ +function wat(b) { + b(); +}`}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageJS.ts b/tests/cases/fourslash/codeFixInferFromUsageJS.ts new file mode 100644 index 00000000000..62c9d1bf90b --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageJS.ts @@ -0,0 +1,12 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: test.js +////[|var foo;|] +////function f() { +//// foo += 2; +////} + +verify.rangeAfterCodeFix("/** @type {number} */\nvar foo;",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts new file mode 100644 index 00000000000..dc52286a906 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts @@ -0,0 +1,14 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js + +/////** @typedef {{ [|p |]}} I */ +/////** @type {I} */ +////var i; +////i.p = 0; + + +verify.rangeAfterCodeFix("p: number", undefined, undefined, 1); diff --git a/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts b/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts new file mode 100644 index 00000000000..cb86347cb9f --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts @@ -0,0 +1,30 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @strictNullChecks: true +// @Filename: important.js +////class C { +//// constructor() { +//// [|this.p|] = undefined; +//// } +//// method() { +//// this.p.push(1) +//// } +////} + + +// Note: Should be number[] | undefined, but inference currently privileges assignments +// over usage (even when the only result is undefined) and infers only undefined. +verify.fileAfterCodeFix( +`class C { + constructor() { + /** @type {undefined} */ + this.p = undefined; + } + method() { + this.p.push(1) + } +} +`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts b/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts new file mode 100644 index 00000000000..8f544df4323 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts @@ -0,0 +1,23 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js + +//// function f([|a, b, c, d, e = 0, ...d |]) { +//// } +//// f(1, "string", { a: 1 }, {shouldNotBeHere: 2}, {shouldNotBeHere: 2}, 3, "string"); + + +verify.fileAfterCodeFix( +`/** + * @param {number} a + * @param {string} b + * @param {{ a: number; }} c + * @param {{ shouldNotBeHere: number; }} d + * @param {(string | number)[]} d + */ +function f(a, b, c, d, e = 0, ...d ) { +} +f(1, "string", { a: 1 }, {shouldNotBeHere: 2}, {shouldNotBeHere: 2}, 3, "string");`, undefined, 6); diff --git a/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts b/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts new file mode 100644 index 00000000000..b6b8fe4c25f --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts @@ -0,0 +1,17 @@ +/// +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js + +////function f([|a|]) { +//// return a[0] + 1; +////} + +verify.fileAfterCodeFix( +`/** + * @param {number[]} a + */ +function f(a) { + return a[0] + 1; +}`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts b/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts new file mode 100644 index 00000000000..cc00c1ddb5d --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts @@ -0,0 +1,21 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js +////function f([|a|]){ +//// a; +////} +////f(); +////f(1); + +verify.fileAfterCodeFix( +`/** + * @param {number} [a] + */ +function f(a) { + a; +} +f(); +f(1);`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts b/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts new file mode 100644 index 00000000000..67795b6a178 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts @@ -0,0 +1,29 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @strictNullChecks: true +// @Filename: important.js +/////** +//// * @param {*} y +//// */ +////function f(x, y, z) { +//// return x +////} +////f(1, 2, 3) + +verify.fileAfterCodeFix( +` +/** + * @param {*} y + */ +/** + * @param {number} x + * @param {number} z + */ +function f(x, y, z) { + return x +} +f(1, 2, 3) +`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts b/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts new file mode 100644 index 00000000000..a52c66312fc --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts @@ -0,0 +1,34 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js + +////function foo([|a, m, x|]) { +//// a.b.c; +//// +//// var numeric = 0; +//// numeric = m.n(); +//// +//// x.y.z +//// x.y.z.push(0); +//// return x.y.z +////} + +verify.fileAfterCodeFix( +`/** + * @param {{ b: { c: any; }; }} a + * @param {{ n: () => number; }} m + * @param {{ y: { z: number[]; }; }} x + */ +function foo(a, m, x) { + a.b.c; + + var numeric = 0; + numeric = m.n(); + + x.y.z + x.y.z.push(0); + return x.y.z +}`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts new file mode 100644 index 00000000000..0504816c597 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts @@ -0,0 +1,27 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js +/////** @param {number} a */ +////function f(a, [|...rest|]){ +//// a; rest; +////} +////f(1); +////f(2, "s1"); +////f(3, false, "s2"); +////f(4, "s1", "s2", false, "s4"); + +verify.fileAfterCodeFix( +`/** @param {number} a */ +/** + * @param {(string | boolean)[]} rest + */ +function f(a, ...rest){ + a; rest; +} +f(1); +f(2, "s1"); +f(3, false, "s2"); +f(4, "s1", "s2", false, "s4");`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts new file mode 100644 index 00000000000..bda7090ba06 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts @@ -0,0 +1,21 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js +/////** @param {number} a */ +////function f(a, [|...rest |]){ +//// a; +//// rest.push(22); +////} + +verify.fileAfterCodeFix( +`/** @param {number} a */ +/** + * @param {number[]} rest + */ +function f(a, ...rest){ + a; + rest.push(22); +}`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts new file mode 100644 index 00000000000..36582bfa7db --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts @@ -0,0 +1,27 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js +/////** @param {number} a */ +////function f(a: number, [|...rest|]){ +//// a; rest; +////} +////f(1); +////f(2, "s1"); +////f(3, "s1", "s2"); +////f(3, "s1", "s2", "s3", "s4"); + +verify.fileAfterCodeFix( +`/** @param {number} a */ +/** + * @param {string[]} rest + */ +function f(a: number, ...rest){ + a; rest; +} +f(1); +f(2, "s1"); +f(3, "s1", "s2"); +f(3, "s1", "s2", "s3", "s4");`, undefined, 4); diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetter2.ts b/tests/cases/fourslash/codeFixInferFromUsageSetter2.ts deleted file mode 100644 index d058bc2787c..00000000000 --- a/tests/cases/fourslash/codeFixInferFromUsageSetter2.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -// @noImplicitAny: true -////class C { -//// set [|x(v)|] { -//// v; -//// } -////} -////(new C).x = 1; - -verify.rangeAfterCodeFix("x(v: number)", undefined, undefined, 1); \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts new file mode 100644 index 00000000000..71621f48239 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts @@ -0,0 +1,24 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js +////class C { +//// set [|x(v)|] { +//// v; +//// } +////} +////(new C).x = 1; + +verify.fileAfterCodeFix( +` +class C { + /** + * @param {number} v + */ + set x(v) { + v; + } +} +(new C).x = 1;`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleType.ts b/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleType.ts index b56c6e05f69..269f67f7cf7 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleType.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleType.ts @@ -18,7 +18,7 @@ verify.codeFix({ description: "Infer type of 'x' from usage", newFileContent: `export class C { - set x(val: Promise) { val; } + set x(val: Promise) { val; } method() { this.x = import("./a"); } }`, }); diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts new file mode 100644 index 00000000000..7620b969234 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts @@ -0,0 +1,36 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true + +// @Filename: /promise.d.ts +////interface Promise { +////} +////declare var Promise: Promise; + +// @Filename: /a.js +////export class D {} +////export default new D(); + +// @Filename: /b.js +////export class C { +//// set [|x|](val) { val; } +//// method() { this.x = import("./a"); } +////} + +goTo.file("/b.js"); +verify.codeFix({ + index: 2, + description: "Infer type of 'x' from usage", + newFileContent: +`export class C { + /** + * @param {Promise} val + */ + set x(val) { val; } + method() { this.x = import("./a"); } +}`, +}); + diff --git a/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts new file mode 100644 index 00000000000..f78a70aa14a --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts @@ -0,0 +1,19 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @Filename: important.js +////class C {m(x) {return x;}} +////var c = new C() +////c.m(1) + +verify.fileAfterCodeFix( +` +class C {/** + * @param {number} x + */ + m(x) {return x;}} +var c = new C() +c.m(1)`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts b/tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts new file mode 100644 index 00000000000..5182e80969e --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts @@ -0,0 +1,23 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @Filename: important.js + +////function f([|a|]) { +//// return a['hi']; +////} + +verify.codeFix({ + index: 2, + description: "Infer parameter types from usage", + newFileContent: +`/** + * @param {{ [x: string]: any; }} a + */ +function f(a) { + return a['hi']; +}`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts new file mode 100644 index 00000000000..0e88a30b96b --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts @@ -0,0 +1,18 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @Filename: important.js +////[|var x; +////function f() { +//// x++; +////}|] + +verify.rangeAfterCodeFix(`/** @type {number} */ +var x; +function f() { + x++; +} +`, /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts b/tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts new file mode 100644 index 00000000000..8e96fd08916 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts @@ -0,0 +1,14 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @Filename: important.js + +////[|var x;|] +////function f() { +//// x++; +////} + +verify.rangeAfterCodeFix("/** @type {number } */\nvar x;", /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsage_allJS.ts b/tests/cases/fourslash/codeFixInferFromUsage_allJS.ts new file mode 100644 index 00000000000..00e44660a98 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsage_allJS.ts @@ -0,0 +1,48 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @strictNullChecks: true +// @Filename: important.js + +////function f(x, y) { +//// x += 0; +//// y += ""; +////} +//// +////function g(z) { +//// return z * 2; +////} +//// +////let x = null; +////function h() { +//// if (!x) x = 2; +////} + +verify.codeFixAll({ + fixId: "inferFromUsage", + fixAllDescription: "Infer all types from usage", + newFileContent: +`/** + * @param {number} x + * @param {string} y + */ +function f(x, y) { + x += 0; + y += ""; +} + +/** + * @param {number} z + */ +function g(z) { + return z * 2; +} + +/** @type {number | null} */ +let x = null; +function h() { + if (!x) x = 2; +}`, +}); diff --git a/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts b/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts index 1389a50935b..478b2a7c647 100644 --- a/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts +++ b/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts @@ -28,5 +28,5 @@ verify.codeFix({ foo1(arg0: () => number, arg1: () => string, arg2: () => boolean): any { throw new Error("Method not implemented."); } - ` + `, }); diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts index b830ccad746..a456299c68a 100644 --- a/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts @@ -6,6 +6,11 @@ const [r0, r1] = test.ranges(); verify.getSuggestionDiagnostics([ + { + message: "Parameter 'p' implicitly has an 'any' type.", + range: r0, + code: 7006, + }, { message: "'p' is declared but its value is never read.", range: r0, diff --git a/tests/cases/fourslash/commentsCommentParsing.ts b/tests/cases/fourslash/commentsCommentParsing.ts index df3adca4c87..8f7d35ce0f9 100644 --- a/tests/cases/fourslash/commentsCommentParsing.ts +++ b/tests/cases/fourslash/commentsCommentParsing.ts @@ -244,8 +244,18 @@ verify.quickInfoAt("13q", "function noHelpComment2(): void"); verify.signatureHelp({ marker: "14", docComment: "" }); verify.quickInfoAt("14q", "function noHelpComment3(): void"); -goTo.marker('15'); -verify.completionListContains("sum", "function sum(a: number, b: number): number", "Adds two integers and returns the result"); +verify.completions({ + marker: "15", + includes: { + name: "sum", + text: "function sum(a: number, b: number): number", + documentation: "Adds two integers and returns the result", + tags: [ + { name: "param", text: "a first number" }, + { name: "param", text: "b second number" }, + ], + }, +}); const addTags: ReadonlyArray = [ { name: "param", text: "a first number" }, diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts new file mode 100644 index 00000000000..59b2d7a9539 --- /dev/null +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts @@ -0,0 +1,36 @@ +/// + +// Should give completions based on typesVersions + +// @Filename: node_modules/ext/package.json +//// { +//// "name": "ext", +//// "version": "1.0.0", +//// "types": "index", +//// "typesVersions": { +//// ">=3.1.0-0": { "*" : ["ts3.1/*"] } +//// } +//// } + +// @Filename: node_modules/ext/index.d.ts +//// export {}; + +// @Filename: node_modules/ext/aaa.d.ts +//// export {}; + +// @Filename: node_modules/ext/ts3.1/index.d.ts +//// export {}; + +// @Filename: node_modules/ext/ts3.1/zzz.d.ts +//// export {}; + +// @Filename: main.ts +//// import * as ext1 from "ext//*import_as0*/ +//// import ext2 = require("ext//*import_equals0*/ +//// var ext2 = require("ext//*require0*/ + +verify.completions({ + marker: test.markerNames(), + exact: ["aaa", "index", "ts3.1", "zzz"], + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionListForStringUnion.ts b/tests/cases/fourslash/completionListForStringUnion.ts index 14e5979efbd..98755ea1e41 100644 --- a/tests/cases/fourslash/completionListForStringUnion.ts +++ b/tests/cases/fourslash/completionListForStringUnion.ts @@ -1,12 +1,11 @@ /// -//// type A = 'fooooo' | 'barrrrr'; +//// type A = 'foo' | 'bar' | 'baz'; //// type B = {}; -//// type C = B<'fooooo' | '/**/'> +//// type C = B<'foo' | '/**/'> - -goTo.marker(); -verify.completionListContains("fooooo"); -verify.completionListContains("barrrrr"); +verify.completions({ marker: "", exact: ["bar", "baz"] }); edit.insert("b"); -verify.completionListContains("barrrrr"); +verify.completions({ exact: ["bar", "baz"] }); +edit.insert("ar"); +verify.completions({ exact: ["bar", "baz"] }); diff --git a/tests/cases/fourslash/completionsAfterAsyncInObjectLiteral.ts b/tests/cases/fourslash/completionsAfterAsyncInObjectLiteral.ts new file mode 100644 index 00000000000..fa1d9a60fc6 --- /dev/null +++ b/tests/cases/fourslash/completionsAfterAsyncInObjectLiteral.ts @@ -0,0 +1,5 @@ +/// + +////const x: { m(): Promise } = { async /**/ }; + +verify.completions({ marker: "", exact: "m" }); diff --git a/tests/cases/fourslash/completionsDotInObjectLiteral.ts b/tests/cases/fourslash/completionsDotInObjectLiteral.ts new file mode 100644 index 00000000000..171e8d2886b --- /dev/null +++ b/tests/cases/fourslash/completionsDotInObjectLiteral.ts @@ -0,0 +1,10 @@ +/// + +////const o = { +//// a: 1, +//// [|.|]/**/ +////[|}|]; + +verify.getSyntacticDiagnostics(test.ranges().map((range): FourSlashInterface.Diagnostic => + ({ code: 1003, message: "Identifier expected.", range }))); +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionsImport_importType.ts b/tests/cases/fourslash/completionsImport_importType.ts index b1b69a9a8d0..3c371980b90 100644 --- a/tests/cases/fourslash/completionsImport_importType.ts +++ b/tests/cases/fourslash/completionsImport_importType.ts @@ -3,13 +3,14 @@ // @allowJs: true // @Filename: /a.js -////export const x = 0; -////export class C {} -/////** @typedef {number} T */ +//// export const x = 0; +//// export class C {} +//// /** @typedef {number} T */ // @Filename: /b.js -/////** @type {/*0*/} */ -/////** @type {/*1*/} */ +//// export const m = 0; +//// /** @type {/*0*/} */ +//// /** @type {/*1*/} */ verify.completions({ marker: ["0", "1"], @@ -43,6 +44,7 @@ verify.applyCodeActionFromCompletion("0", { newFileContent: `import { C } from "./a"; +export const m = 0; /** @type {} */ /** @type {} */`, }); @@ -55,6 +57,7 @@ verify.applyCodeActionFromCompletion("1", { newFileContent: `import { C } from "./a"; +export const m = 0; /** @type {} */ /** @type {import("./a").} */`, }); diff --git a/tests/cases/fourslash/completionsTriggerCharacter.ts b/tests/cases/fourslash/completionsTriggerCharacter.ts index a58ff2edc5f..ad3d633371f 100644 --- a/tests/cases/fourslash/completionsTriggerCharacter.ts +++ b/tests/cases/fourslash/completionsTriggerCharacter.ts @@ -2,6 +2,7 @@ // @jsx: preserve +/////** @/*tag*/ */ ////// + +// @allowJs: true +// @noLib: true + +// @Filename: /a.js +/////** @type/**/ */ +////const x = 0; + +goTo.marker(); +verify.quickInfoIs(""); +edit.insert(" "); +verify.quickInfoIs(""); diff --git a/tests/cases/fourslash/findAllReferencesDynamicImport3.ts b/tests/cases/fourslash/findAllReferencesDynamicImport3.ts index 636e640ceb3..371369ac39c 100644 --- a/tests/cases/fourslash/findAllReferencesDynamicImport3.ts +++ b/tests/cases/fourslash/findAllReferencesDynamicImport3.ts @@ -10,4 +10,5 @@ verify.referenceGroups(r1, [ { definition: "function bar(): string", ranges: [r0] }, { definition: "var bar: () => string", ranges: [r1] }, ]); -verify.rangesAreRenameLocations(); +verify.renameLocations(r0, [r0, { range: r1, suffixText: ": bar" }]); +verify.renameLocations(r1, [{ range: r1, prefixText: "bar: " }]) diff --git a/tests/cases/fourslash/findAllRefsDestructureGetter.ts b/tests/cases/fourslash/findAllRefsDestructureGetter.ts index b21e6186eb2..763d3cfb0e5 100644 --- a/tests/cases/fourslash/findAllRefsDestructureGetter.ts +++ b/tests/cases/fourslash/findAllRefsDestructureGetter.ts @@ -9,14 +9,16 @@ ////[|x|]; [|y|]; const [x0, y0, x1, y1, x2, y2] = test.ranges(); -verify.referenceGroups(x0, [{ definition: "(property) Test.x: number", ranges: [x0, x1, x2] }]); -verify.referenceGroups([x1, x2], [ +verify.referenceGroups(x0, [{ definition: "(property) Test.x: number", ranges: [x0, x1] }]); +verify.referenceGroups(x1, [ { definition: "(property) Test.x: number", ranges: [x0] }, { definition: "const x: number", ranges: [x1, x2] }, ]); +verify.referenceGroups(x2, [{ definition: "const x: number", ranges: [x1, x2] }]); -verify.referenceGroups(y0, [{ definition: "(property) Test.y: number", ranges: [y0, y1, y2] }]); -verify.referenceGroups([y1, y2], [ +verify.referenceGroups(y0, [{ definition: "(property) Test.y: number", ranges: [y0, y1] }]); +verify.referenceGroups(y1, [ { definition: "(property) Test.y: number", ranges: [y0] }, { definition: "const y: number", ranges: [y1, y2] }, ]); +verify.referenceGroups(y2, [{ definition: "const y: number", ranges: [y1, y2] }]); diff --git a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName04.ts b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName04.ts index fe0d659f0ec..c3bebdb2623 100644 --- a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName04.ts +++ b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName04.ts @@ -14,9 +14,9 @@ const ranges = test.ranges(); const [r0, r1, r2, r3] = ranges; -verify.referenceGroups([r0, r1], [{ definition: "(property) I.property1: number", ranges }]); -verify.referenceGroups([r2, r3], [ +verify.referenceGroups([r0, r1], [{ definition: "(property) I.property1: number", ranges: [r0, r1, r2] }]); +verify.referenceGroups(r2, [ { definition: "(property) I.property1: number", ranges: [r0, r1] }, - { definition: "var property1: number", ranges: [r2, r3] } + { definition: "var property1: number", ranges: [r2, r3] }, ]); - +verify.referenceGroups(r3, [{ definition: "var property1: number", ranges: [r2, r3] }]); diff --git a/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts b/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts index c944f2468c5..7fe0696f952 100644 --- a/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts +++ b/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts @@ -8,12 +8,12 @@ ////export = [|T|]; // @Filename: /b.ts -////const x: import("[|./a|]") = 0; -////const y: import("[|./a|]").U = ""; +////const x: import("[|./[|a|]|]") = 0; +////const y: import("[|./[|a|]|]").U = ""; verify.noErrors(); -const [r0, r1, r2, r3, r4] = test.ranges(); +const [r0, r1, r2, r3, r3b, r4, r4b] = test.ranges(); verify.referenceGroups(r0, [{ definition: "type T = number\nnamespace T", ranges: [r0, r2, r3] }]); verify.referenceGroups(r1, [{ definition: "namespace T", ranges: [r1, r2] }]); verify.referenceGroups(r2, [{ definition: "type T = number\nnamespace T", ranges: [r0, r1, r2, r3] }]); @@ -25,7 +25,7 @@ verify.referenceGroups([r3, r4], [ verify.renameLocations(r0, [r0, r2]); verify.renameLocations(r1, [r1, r2]); verify.renameLocations(r2, [r0, r1, r2]); -for (const range of [r3, r4]) { +for (const range of [r3b, r4b]) { goTo.rangeStart(range); - verify.renameInfoFailed(); + verify.renameInfoSucceeded(/*displayName*/ "/a.ts", /*fullDisplayName*/ "/a.ts", /*kind*/ "module", /*kindModifiers*/ "", /*fileToRename*/ "/a.ts", range); } diff --git a/tests/cases/fourslash/findAllRefs_jsEnum.ts b/tests/cases/fourslash/findAllRefs_jsEnum.ts new file mode 100644 index 00000000000..c77b24256bf --- /dev/null +++ b/tests/cases/fourslash/findAllRefs_jsEnum.ts @@ -0,0 +1,16 @@ +/// + +// @allowJs: true + +// @Filename: /a.js +/////** @enum {string} */ +////const [|{| "isWriteAccess": true, "isDefinition": true |}E|] = { A: "" }; +////[|E|]["A"]; +/////** @type {[|E|]} */ +////const e = [|E|].A; + +verify.singleReferenceGroup( +`enum E +const E: { + A: string; +}`); diff --git a/tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts b/tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts new file mode 100644 index 00000000000..824839ff4af --- /dev/null +++ b/tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts @@ -0,0 +1,7 @@ +/// +////someCall( +//// /*start*/"firstParameter",/*end*/ +//// "something else" +////); + +format.selection("start", "end"); \ No newline at end of file diff --git a/tests/cases/fourslash/formatWithTabs.ts b/tests/cases/fourslash/formatWithTabs.ts index c33808bd26a..e1b8878f4a9 100644 --- a/tests/cases/fourslash/formatWithTabs.ts +++ b/tests/cases/fourslash/formatWithTabs.ts @@ -13,4 +13,4 @@ format.document(); verify.currentFileContentIs( `const foo = [ 1 -];`); \ No newline at end of file +];`); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 2d73be1a917..4603d61a286 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -129,7 +129,7 @@ declare namespace FourSlashInterface { eachMarker(markers: ReadonlyArray, action: (marker: Marker, index: number) => void): void; eachMarker(action: (marker: Marker, index: number) => void): void; rangeStart(range: Range): void; - eachRange(action: () => void): void; + eachRange(action: (range: Range) => void): void; bof(): void; eof(): void; implementation(): void; @@ -284,7 +284,7 @@ declare namespace FourSlashInterface { docCommentTemplateAt(markerName: string | FourSlashInterface.Marker, expectedOffset: number, expectedText: string): void; noDocCommentTemplateAt(markerName: string | FourSlashInterface.Marker): void; rangeAfterCodeFix(expectedText: string, includeWhiteSpace?: boolean, errorCode?: number, index?: number): void; - codeFixAll(options: { fixId: string, fixAllDescription: string, newFileContent: string, commands?: {}[] }): void; + codeFixAll(options: { fixId: string, fixAllDescription: string, newFileContent: NewFileContent, commands?: {}[] }): void; fileAfterApplyingRefactorAtMarker(markerName: string, expectedContent: string, refactorNameToApply: string, actionName: string, formattingOptions?: FormatCodeOptions): void; rangeIs(expectedText: string, includeWhiteSpace?: boolean): void; fileAfterApplyingRefactorAtMarker(markerName: string, expectedContent: string, refactorNameToApply: string, formattingOptions?: FormatCodeOptions): void; @@ -299,7 +299,7 @@ declare namespace FourSlashInterface { rangesAreDocumentHighlights(ranges?: Range[], options?: VerifyDocumentHighlightsOptions): void; rangesWithSameTextAreDocumentHighlights(): void; documentHighlightsOf(startRange: Range, ranges: Range[], options?: VerifyDocumentHighlightsOptions): void; - completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]): void; + completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string, tags?: JSDocTagInfo[]): void; /** * This method *requires* a contiguous, complete, and ordered stream of classifications for a file. */ @@ -315,9 +315,9 @@ declare namespace FourSlashInterface { text: string; textSpan?: TextSpan; }[]): void; - renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string): void; + renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string, fileToRename?: string, range?: Range): void; renameInfoFailed(message?: string): void; - renameLocations(startRanges: ArrayOrSingle, options: Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges: Range[] }): void; + renameLocations(startRanges: ArrayOrSingle, options: RenameLocationsOptions): void; /** Verify the quick info available at the current marker. */ quickInfoIs(expectedText: string, expectedDocumentation?: string): void; @@ -331,7 +331,7 @@ declare namespace FourSlashInterface { verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; - }, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: { name: string, text?: string }[]): void; + }, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: { name: string, text?: string }[] | undefined): void; getSyntacticDiagnostics(expected: ReadonlyArray): void; getSemanticDiagnostics(expected: ReadonlyArray): void; getSuggestionDiagnostics(expected: ReadonlyArray): void; @@ -348,6 +348,8 @@ declare namespace FourSlashInterface { readonly preferences?: UserPreferences; }): void; noMoveToNewFile(): void; + + generateTypes(...options: GenerateTypesOptions[]): void; } class edit { backspace(count?: number): void; @@ -550,6 +552,7 @@ declare namespace FourSlashInterface { // details readonly text?: string, readonly documentation?: string, + readonly tags?: ReadonlyArray; readonly sourceDisplay?: string, }; @@ -632,12 +635,26 @@ declare namespace FourSlashInterface { } interface JSDocTagInfo { - name: string; - text: string | undefined; + readonly name: string; + readonly text: string | undefined; + } + + interface GenerateTypesOptions { + readonly name?: string; + readonly value: unknown; + readonly output?: string | undefined; + readonly outputBaseline?: string; } type ArrayOrSingle = T | ReadonlyArray; type NewFileContent = string | { readonly [fileName: string]: string }; + + type RenameLocationsOptions = ReadonlyArray | { + readonly findInStrings?: boolean; + readonly findInComments?: boolean; + readonly ranges: ReadonlyArray; + } + type RenameLocationOptions = Range | { readonly range: Range, readonly prefixText?: string, readonly suffixText?: string }; } declare function verifyOperationIsCancelled(f: any): void; declare var test: FourSlashInterface.test_; diff --git a/tests/cases/fourslash/generateTypes.ts b/tests/cases/fourslash/generateTypes.ts new file mode 100644 index 00000000000..bfe521e2046 --- /dev/null +++ b/tests/cases/fourslash/generateTypes.ts @@ -0,0 +1,109 @@ +/// + +////dummy text + +verify.generateTypes( +{ + value: 0, + output: +`export = example; +declare const example: number;`, +}, +{ + value: (x, y) => x + y, + output: +`export = example; +declare function example(x: any, y: any): void;`, +}, +{ + // non-arrow functions have different toString(), so important to test + value: function(x, y) { + return x * y; + function inner() { + arguments; // Should not affect type inference + } + }, + output: +`export = example; +declare function example(x: any, y: any): any;`, +}, +{ + value: function(x) { arguments; }, + output: +`export = example; +declare function example(x: any, ...args: any[]): void;`, +}, + +{ + value: ({ default() {} }), + output: +`export default function _default(): void;`, +}, + +{ + value: ({ default: class {} }), + output: +`export default class _default { +}`, +}, + +{ + value: new Date(), + output: +`export = example; +declare const example: Date;`, +}, + +{ + value: [0], + output: +`export = example; +declare const example: number[];`, +}, +{ + value: [() => 0, () => ""], + output: +`export = example; +declare const example: Function[];`, +}, +{ + value: (() => { + const a = []; + a.push(a); + return a; + })(), + output: +`export = example; +declare const example: any[];`, +}, +{ + value: (() => { + const o = { + default: 0, + a: 0, + b: "", + self: null, + fn: x => x, + ns1: { x: 0, default: 0 }, + ns2: { fn: x => x, default: 0 }, + }; + o.self = o; + return o; + })(), + output: +`export const a: number; +export const b: string; +export default _default; +export const _default: number; +export function fn(x: any): void; +export const ns1: { + default: number; + x: number; +}; +export namespace ns2 { + function fn(x: any): void; +} +// Circular reference from example +export const self: any;`, +}, +); diff --git a/tests/cases/fourslash/generateTypes_baselines.ts b/tests/cases/fourslash/generateTypes_baselines.ts new file mode 100644 index 00000000000..a8363b30283 --- /dev/null +++ b/tests/cases/fourslash/generateTypes_baselines.ts @@ -0,0 +1,35 @@ +/// + +////dummy text + +verify.generateTypes( + // would like to test against the real "global" but that may vary between node versions. + { + value: { + Array: ignore(Array, ["values"]), + Boolean, + Date, + Math, + Number, + RegExp, + String: ignore(String, ["padStart", "padEnd", "trimStart", "trimEnd"]), + Symbol: ignore(Symbol, ["asyncIterator"]), + }, + outputBaseline: "global", + }, + { value: require("lodash"), outputBaseline: "lodash" }, +); + +// Ignore properties only present in newer versions of node. +function ignore(Cls: Function, ignored: ReadonlyArray): Function { + class Copy {} + for (const name of Object.getOwnPropertyNames(Cls)) { + if (ignored.includes(name) || name === "arguments" || name === "caller" || name === "name" || name === "length" || name === "prototype") continue; + Copy[name] = Cls[name]; + } + for (const name of Object.getOwnPropertyNames(Cls.prototype)) { + if (ignored.includes(name)) continue; + Copy.prototype[name] = Cls.prototype[name]; + } + return Copy; +} diff --git a/tests/cases/fourslash/generateTypes_classes.ts b/tests/cases/fourslash/generateTypes_classes.ts new file mode 100644 index 00000000000..94fd43fe529 --- /dev/null +++ b/tests/cases/fourslash/generateTypes_classes.ts @@ -0,0 +1,109 @@ +/// + +////dummy text + +verify.generateTypes( +{ + value: class {}, + output: +`export = example; +declare class example { +}`, +}, + +{ + value: class { + constructor(x) { + (this as any).x = x; + // Code inside this function should be ignored + function f(this: any) { + this.y = 0; + } + // Same for this class + class Other { constructor() { (this as any).z = 0; } } + } + }, + output: +`export = example; +declare class example { + constructor(x: any); + x: any; +}`, +}, +{ + value: { x: 0, export: 0 }, + output: `export const x: number;`, +}, +{ + value: (() => { + class Super { + superField = 0; // TODO: climb to prototype.constructor and get instance fields? + superMethod() {} + static superStaticMethod() {} + } + class C extends Super { + constructor() { + super(); + (this as any)._privateField = 0; + (this as any).field = 0; + } + + _privateMethod() {} + method(_p) { + (this as any).otherField = 0; // TODO: include this in output? + } + + static _privateStatic() {} + static staticMethod(_s: any) {} + static staticMethodWithNoNamespaceMembers(_p: any) {} + + static _privateStaticField = 0; + static staticField = 0; + static innerClass = class {}; + } + (C.prototype as any).prototypeNonFunction = 0; // ignored + (C.staticMethod as any).staticMethodProperty = 0; + (C.staticMethod as any)._staticFieldPrivateMember = 0; + (C.prototype.method as any).methodMember = 0; // ignored + // Non-identifier names should be ignored. + (C as any)["&"] = function() {}; + (C.prototype as any)["&"] = function() {}; + return C; + })(), + output: +`export = example; +declare class example { + static staticField: number; + static staticMethodWithNoNamespaceMembers(_p: any): void; + static superStaticMethod(): void; + field: any; + method(_p: any): void; + superMethod(): void; +} +declare namespace example { + class innerClass { + } + function staticMethod(_s: any): void; + namespace staticMethod { + const staticMethodProperty: number; + } +}`, +}, + +{ + value: (() => { + function F() { this.x = 0; } + (F as any).staticMethod = function() {} + F.prototype.method = function() { } + return F; + })(), + output: +`export = example; +declare class example { + static staticMethod(): void; + x: any; + method(): void; +}`, +}, + +); diff --git a/tests/cases/fourslash/getEditsForFileRename_notAffectedByJsFile.ts b/tests/cases/fourslash/getEditsForFileRename_notAffectedByJsFile.ts new file mode 100644 index 00000000000..f1b1497f2ef --- /dev/null +++ b/tests/cases/fourslash/getEditsForFileRename_notAffectedByJsFile.ts @@ -0,0 +1,18 @@ +/// + +// @Filename: /a.ts +////export const x = 0; + +// @Filename: /a.js +////exports.x = 0; + +// @Filename: /b.ts +////import { x } from "./a"; + +verify.getEditsForFileRename({ + oldPath: "/a.ts", + newPath: "/a2.ts", + newFileContents: { + "/b.ts": 'import { x } from "./a2";', + }, +}); diff --git a/tests/cases/fourslash/getOccurrencesIsDefinitionOfBindingPattern.ts b/tests/cases/fourslash/getOccurrencesIsDefinitionOfBindingPattern.ts index 58814b45e99..32fec74d162 100644 --- a/tests/cases/fourslash/getOccurrencesIsDefinitionOfBindingPattern.ts +++ b/tests/cases/fourslash/getOccurrencesIsDefinitionOfBindingPattern.ts @@ -3,8 +3,8 @@ ////const z = [|x|]; const [r0, r1, r2] = test.ranges(); -verify.referenceGroups([r0, r2], [ - { definition: "const x: number", ranges: [r0, r2] }, - { definition: "(property) x: number", ranges: [r1] }, -]); -verify.referenceGroups(r1, [{ definition: "(property) x: number", ranges: [r0, r1, r2] }]); +const local = { definition: "const x: number", ranges: [r0, r2] }; +const prop = { definition: "(property) x: number", ranges: [r1] }; +verify.referenceGroups(r0, [local, prop]); +verify.referenceGroups(r1, [{ ...prop, ranges: [r0, r1] }]); +verify.referenceGroups(r2, [local]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts index 12566de406d..8d86324a934 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts @@ -2,12 +2,12 @@ //// [|f1/*0*/();|] -// @Filename: module.ts +// @Filename: jalapeño.ts //// export function f1() {} //// export var v1 = 5; verify.importFixAtPosition([ -`import { f1 } from "./module"; +`import { f1 } from "./jalapeño"; f1();` ]); diff --git a/tests/cases/fourslash/importNameCodeFix_defaultExport.ts b/tests/cases/fourslash/importNameCodeFix_defaultExport.ts new file mode 100644 index 00000000000..fa8cef71c99 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFix_defaultExport.ts @@ -0,0 +1,18 @@ +/// + +// @allowJs: true +// @checkJs: true + +// @Filename: /a.js +////class C {} +////export default C; + +// @Filename: /b.js +////[|C;|] + +goTo.file("/b.js"); +verify.importFixAtPosition([ +`import C from "./a"; + +C;`, +]); diff --git a/tests/cases/fourslash/jsDocFunctionSignatures8.ts b/tests/cases/fourslash/jsDocFunctionSignatures8.ts index 6853c70daf2..f7f2f4dca5e 100644 --- a/tests/cases/fourslash/jsDocFunctionSignatures8.ts +++ b/tests/cases/fourslash/jsDocFunctionSignatures8.ts @@ -14,4 +14,4 @@ ////} ////var p = new Pers/**/on(); goTo.marker(); -verify.quickInfoIs("function Person(name: string, age: number): void", "Represents a person\na b multiline test"); +verify.quickInfoIs("function Person(name: string, age: number): Person", "Represents a person\na b multiline test"); diff --git a/tests/cases/fourslash/jsDocFunctionSignatures9.ts b/tests/cases/fourslash/jsDocFunctionSignatures9.ts index 6c3342c0a3f..68c906b93ef 100644 --- a/tests/cases/fourslash/jsDocFunctionSignatures9.ts +++ b/tests/cases/fourslash/jsDocFunctionSignatures9.ts @@ -20,4 +20,4 @@ verify.verifyQuickInfoDisplayParts('function', {"text": "void", "kind": "keyword"} ], [{"text": "first line of the comment\n\nthird line", "kind": "text"}], - []); + undefined); diff --git a/tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions.ts b/tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions.ts index c0753bc7159..23fe81fe48e 100644 --- a/tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions.ts +++ b/tests/cases/fourslash/navigationBarAnonymousClassAndFunctionExpressions.ts @@ -18,6 +18,8 @@ //// // These will only show up as childItems. //// function z() {} //// console.log(function() {}) +//// describe("this", 'function', () => {}); +//// [].map(() => {}); ////}) ////(function classes() { //// // Classes show up in top-level regardless of whether they have names or inner declarations. @@ -71,7 +73,15 @@ verify.navigationTree({ "kind": "function", "childItems": [ { - "text": "", + "text": "console.log() callback", + "kind": "function" + }, + { + "text": `describe("this", 'function') callback`, + "kind": "function" + }, + { + "text": `map() callback`, "kind": "function" }, { @@ -185,7 +195,15 @@ verify.navigationBar([ "kind": "function", "childItems": [ { - "text": "", + "text": "console.log() callback", + "kind": "function" + }, + { + "text": `describe("this", 'function') callback`, + "kind": "function" + }, + { + "text": `map() callback`, "kind": "function" }, { diff --git a/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts b/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts new file mode 100644 index 00000000000..3493c4c2cff --- /dev/null +++ b/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts @@ -0,0 +1,31 @@ +/// + +// @allowJs: true +// @module: esnext + +// @Filename: /node_modules/foo/index.d.ts +//// export const fail: number; + +// @Filename: /a.js +//// export const x = 0; +//// export class C {} +//// + +// @Filename: /b.js +//// /**/ + +goTo.file("/b.js"); +goTo.marker(); +verify.not.completionListContains("fail", undefined, undefined, undefined, undefined, undefined, { includeCompletionsForModuleExports: true }); +edit.insert("export const k = 10;\r\nf"); +verify.completionListContains( + { name: "fail", source: "/node_modules/foo/index" }, + "const fail: number", + "", + "const", + undefined, + true, + { + includeCompletionsForModuleExports: true, + sourceDisplay: "./node_modules/foo/index" + }); diff --git a/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts b/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts index b92a920c3b2..f992f4c8e8e 100644 --- a/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts +++ b/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts @@ -4,4 +4,13 @@ ////export {}; ////const a = 1 d; -verify.getSuggestionDiagnostics([]); +// Only give suggestions for nodes that do NOT have parse errors +verify.getSuggestionDiagnostics([{ + message: "Variable 'd' implicitly has an 'any' type.", + code: 7005, + range: { + fileName: "/a.ts", + pos: 23, + end: 24, + } +}]); diff --git a/tests/cases/fourslash/quickInfoPropertyTag.ts b/tests/cases/fourslash/quickInfoPropertyTag.ts index b413a7610e1..e702436ed42 100644 --- a/tests/cases/fourslash/quickInfoPropertyTag.ts +++ b/tests/cases/fourslash/quickInfoPropertyTag.ts @@ -12,5 +12,4 @@ /////** @type {I} */ ////const obj = { /**/x: 10 }; -// TODO: GH#21123 There shouldn't be a " " before "More doc" -verify.quickInfoAt("", "(property) x: number", "Doc\n More doc"); +verify.quickInfoAt("", "(property) x: number", "Doc\nMore doc"); diff --git a/tests/cases/fourslash/refactorConvertToEs6Module_export_named.ts b/tests/cases/fourslash/refactorConvertToEs6Module_export_named.ts index e7ee2908580..481281a47a4 100644 --- a/tests/cases/fourslash/refactorConvertToEs6Module_export_named.ts +++ b/tests/cases/fourslash/refactorConvertToEs6Module_export_named.ts @@ -12,10 +12,10 @@ ////exports.a3 = x => { x; }; ////exports.a4 = x => x; -verify.getSuggestionDiagnostics([{ - message: "File is a CommonJS module; it may be converted to an ES6 module.", - code: 80001, -}]); +const [r0, r1, r2] = test.ranges(); +verify.getSuggestionDiagnostics([ + { message: "File is a CommonJS module; it may be converted to an ES6 module.", code: 80001, range: r0 }, +]); verify.codeFix({ description: "Convert to ES6 module", diff --git a/tests/cases/fourslash/refactorConvertToEs6Module_unexported_uninitialized_var.ts b/tests/cases/fourslash/refactorConvertToEs6Module_unexported_uninitialized_var.ts new file mode 100644 index 00000000000..e9cbaafee58 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToEs6Module_unexported_uninitialized_var.ts @@ -0,0 +1,24 @@ +/// + +// @allowJs: true +// @target: esnext + +// @Filename: /a.js +////var privateUnrelated; +////[|exports.f|] = function() {}; +////privateUnrelated = 1; +////console.log(privateUnrelated); + +verify.getSuggestionDiagnostics([{ + message: "File is a CommonJS module; it may be converted to an ES6 module.", + code: 80001, +}]); + +verify.codeFix({ + description: "Convert to ES6 module", + newFileContent: +`var privateUnrelated; +export function f() {} +privateUnrelated = 1; +console.log(privateUnrelated);`, +}); diff --git a/tests/cases/fourslash/renameDestructuringAssignmentInFor.ts b/tests/cases/fourslash/renameDestructuringAssignmentInFor.ts index 0ef6f672e00..2c8ad51f486 100644 --- a/tests/cases/fourslash/renameDestructuringAssignmentInFor.ts +++ b/tests/cases/fourslash/renameDestructuringAssignmentInFor.ts @@ -6,13 +6,15 @@ ////} ////var elems: I[]; //// -////var p2: number, property1: number; +////var p2: number, [|property1|]: number; ////for ({ [|property1|] } = elems[0]; p2 < 100; p2++) { -//// p2 = property1++; +//// p2 = [|property1|]++; ////} ////for ({ [|property1|]: p2 } = elems[0]; p2 < 100; p2++) { ////} +verify.noErrors(); const ranges = test.ranges(); -const [r0, , r2] = ranges; -verify.renameLocations([r0, r2], ranges); +const [r0, r1, r2, r3, r4] = ranges; +verify.renameLocations([r0, r4], [r0, { range: r2, suffixText: ": property1" }, r4]); +verify.renameLocations([r1, r2, r3], [r1, { range: r2, prefixText: "property1: " }, r3]); diff --git a/tests/cases/fourslash/renameDestructuringAssignmentInFor2.ts b/tests/cases/fourslash/renameDestructuringAssignmentInFor2.ts deleted file mode 100644 index 17173d0da4d..00000000000 --- a/tests/cases/fourslash/renameDestructuringAssignmentInFor2.ts +++ /dev/null @@ -1,20 +0,0 @@ -/// - -////interface I { -//// [|property1|]: number; -//// property2: string; -////} -////var elems: I[]; -//// -////var p2: number, [|property1|]: number; -////for ({ [|property1|] } = elems[0]; p2 < 100; p2++) { -//// p2 = [|property1|]++; -////} -////for ({ [|property1|]: p2 } = elems[0]; p2 < 100; p2++) { -////} - -const ranges = test.ranges(); -const [r0, r1, r2, r3, r4] = ranges; -verify.renameLocations([r0, r4], [r0, r2, r4]); -verify.renameLocations([r1, r3], [r1, r2, r3]); -verify.renameLocations(r2, ranges); diff --git a/tests/cases/fourslash/renameDestructuringAssignmentInForOf.ts b/tests/cases/fourslash/renameDestructuringAssignmentInForOf.ts index b452ca7c9a7..38703a68b99 100644 --- a/tests/cases/fourslash/renameDestructuringAssignmentInForOf.ts +++ b/tests/cases/fourslash/renameDestructuringAssignmentInForOf.ts @@ -6,13 +6,15 @@ ////} ////var elems: I[]; //// -////var property1: number, p2: number; +////var [|property1|]: number, p2: number; ////for ({ [|property1|] } of elems) { -//// property1++; +//// [|property1|]++; ////} ////for ({ [|property1|]: p2 } of elems) { ////} +verify.noErrors(); const ranges = test.ranges(); -const [r0, , r2] = ranges; -verify.renameLocations([r0, r2], ranges); +const [r0, r1, r2, r3, r4] = ranges; +verify.renameLocations([r0, r4], [r0, { range: r2, suffixText: ": property1" }, r4]); +verify.renameLocations([r1, r2, r3], [r1, { range: r2, prefixText: "property1: " }, r3]); diff --git a/tests/cases/fourslash/renameDestructuringAssignmentInForOf2.ts b/tests/cases/fourslash/renameDestructuringAssignmentInForOf2.ts deleted file mode 100644 index b7432e08a26..00000000000 --- a/tests/cases/fourslash/renameDestructuringAssignmentInForOf2.ts +++ /dev/null @@ -1,20 +0,0 @@ -/// - -////interface I { -//// [|property1|]: number; -//// property2: string; -////} -////var elems: I[]; -//// -////var [|property1|]: number, p2: number; -////for ({ [|property1|] } of elems) { -//// [|property1|]++; -////} -////for ({ [|property1|]: p2 } of elems) { -////} - -const ranges = test.ranges(); -const [r0, r1, r2, r3, r4] = ranges; -verify.renameLocations([r0, r4], [r0, r2, r4]); -verify.renameLocations([r1, r3], [r1, r2, r3]); -verify.renameLocations(r2, ranges); diff --git a/tests/cases/fourslash/renameDestructuringAssignmentNestedInArrayLiteral.ts b/tests/cases/fourslash/renameDestructuringAssignmentNestedInArrayLiteral.ts index 57191e6d6ab..292aaf1bf6d 100644 --- a/tests/cases/fourslash/renameDestructuringAssignmentNestedInArrayLiteral.ts +++ b/tests/cases/fourslash/renameDestructuringAssignmentNestedInArrayLiteral.ts @@ -4,10 +4,12 @@ //// [|property1|]: number; //// property2: string; ////} -////var elems: I[], p1: number, property1: number; +////var elems: I[], p1: number, [|property1|]: number; ////[{ [|property1|]: p1 }] = elems; ////[{ [|property1|] }] = elems; const ranges = test.ranges(); -const [r0, r1] = ranges; -verify.renameLocations([r0, r1], ranges); +const [r0, r1, r2, r3] = ranges; +verify.renameLocations([r0, r2], [r0, r2, { range: r3, suffixText: ": property1" }]); +verify.renameLocations([r1, r3], [r1, { range: r3, prefixText: "property1: " }]); + diff --git a/tests/cases/fourslash/renameDestructuringAssignmentNestedInArrayLiteral2.ts b/tests/cases/fourslash/renameDestructuringAssignmentNestedInArrayLiteral2.ts deleted file mode 100644 index 1f18c443ca6..00000000000 --- a/tests/cases/fourslash/renameDestructuringAssignmentNestedInArrayLiteral2.ts +++ /dev/null @@ -1,15 +0,0 @@ -/// - -////interface I { -//// [|property1|]: number; -//// property2: string; -////} -////var elems: I[], p1: number, [|property1|]: number; -////[{ [|property1|]: p1 }] = elems; -////[{ [|property1|] }] = elems; - -const ranges = test.ranges(); -const [r0, r1, r2, r3] = ranges; -verify.renameLocations([r0, r2], [r0, r2, r3]); -verify.renameLocations(r1, [r1, r3]); -verify.renameLocations(r3, ranges); diff --git a/tests/cases/fourslash/renameDestructuringAssignmentNestedInFor.ts b/tests/cases/fourslash/renameDestructuringAssignmentNestedInFor.ts index fe8961aa18c..e83487d15d2 100644 --- a/tests/cases/fourslash/renameDestructuringAssignmentNestedInFor.ts +++ b/tests/cases/fourslash/renameDestructuringAssignmentNestedInFor.ts @@ -7,14 +7,16 @@ //// secondary: string; //// }; ////} -////let multiRobot: MultiRobot; +////let multiRobot: MultiRobot, [|primary|]: string, secondary: string, primaryA: string, secondaryA: string, i: number; ////for ({ skills: { [|primary|]: primaryA, secondary: secondaryA } } = multiRobot, i = 0; i < 1; i++) { -//// console.log(primaryA); +//// primaryA; ////} ////for ({ skills: { [|primary|], secondary } } = multiRobot, i = 0; i < 1; i++) { -//// console.log(primary); +//// [|primary|]; ////} +verify.noErrors(); const ranges = test.ranges(); -const [r0, r1] = ranges; -verify.renameLocations([r0, r1], ranges); +const [r0, r1, r2, r3, r4] = ranges; +verify.renameLocations([r0, r2], [r0, r2, { range: r3, suffixText: ": primary" }]); +verify.renameLocations([r1, r3, r4], [r1, { range: r3, prefixText: "primary: " }, r4]); diff --git a/tests/cases/fourslash/renameDestructuringAssignmentNestedInFor2.ts b/tests/cases/fourslash/renameDestructuringAssignmentNestedInFor2.ts index c5e7212c99b..e83487d15d2 100644 --- a/tests/cases/fourslash/renameDestructuringAssignmentNestedInFor2.ts +++ b/tests/cases/fourslash/renameDestructuringAssignmentNestedInFor2.ts @@ -7,16 +7,16 @@ //// secondary: string; //// }; ////} -////let multiRobot: MultiRobot, [|primary|]: string; +////let multiRobot: MultiRobot, [|primary|]: string, secondary: string, primaryA: string, secondaryA: string, i: number; ////for ({ skills: { [|primary|]: primaryA, secondary: secondaryA } } = multiRobot, i = 0; i < 1; i++) { -//// console.log(primaryA); +//// primaryA; ////} ////for ({ skills: { [|primary|], secondary } } = multiRobot, i = 0; i < 1; i++) { -//// console.log([|primary|]); +//// [|primary|]; ////} +verify.noErrors(); const ranges = test.ranges(); const [r0, r1, r2, r3, r4] = ranges; -verify.renameLocations([r0, r2], [r0, r2, r3]); -verify.renameLocations([r1, r4], [r1, r3, r4]); -verify.renameLocations(r3, ranges); +verify.renameLocations([r0, r2], [r0, r2, { range: r3, suffixText: ": primary" }]); +verify.renameLocations([r1, r3, r4], [r1, { range: r3, prefixText: "primary: " }, r4]); diff --git a/tests/cases/fourslash/renameDestructuringAssignmentNestedInForOf.ts b/tests/cases/fourslash/renameDestructuringAssignmentNestedInForOf.ts index 7d057600748..6a9eb6235b7 100644 --- a/tests/cases/fourslash/renameDestructuringAssignmentNestedInForOf.ts +++ b/tests/cases/fourslash/renameDestructuringAssignmentNestedInForOf.ts @@ -8,13 +8,15 @@ //// }; ////} ////let multiRobots: MultiRobot[]; +////let [|primary|]: string, secondary: string, primaryA: string, secondaryA: string; ////for ({ skills: { [|primary|]: primaryA, secondary: secondaryA } } of multiRobots) { -//// console.log(primaryA); +//// primaryA; ////} ////for ({ skills: { [|primary|], secondary } } of multiRobots) { -//// console.log(primary); +//// [|primary|]; ////} -const ranges = test.ranges(); -const [r0, r1] = ranges; -verify.renameLocations([r0, r1], ranges); +verify.noErrors(); +const [r0, r1, r2, r3, r4] = test.ranges(); +verify.renameLocations([r0, r2], [r0, r2, { range: r3, suffixText: ": primary" }]); +verify.renameLocations([r1, r3, r4], [r1, { range: r3, prefixText: "primary: " }, r4]) diff --git a/tests/cases/fourslash/renameDestructuringAssignmentNestedInForOf2.ts b/tests/cases/fourslash/renameDestructuringAssignmentNestedInForOf2.ts index 74dfda39bc2..7c5c288ea78 100644 --- a/tests/cases/fourslash/renameDestructuringAssignmentNestedInForOf2.ts +++ b/tests/cases/fourslash/renameDestructuringAssignmentNestedInForOf2.ts @@ -17,6 +17,5 @@ const ranges = test.ranges(); const [r0, r1, r2, r3, r4] = ranges; -verify.renameLocations([r0, r2], [r0, r2, r3]); -verify.renameLocations([r1, r4], [r1, r3, r4]); -verify.renameLocations(r3, ranges); +verify.renameLocations([r0, r2], [r0, r2, { range: r3, suffixText: ": primary" }]); +verify.renameLocations([r1, r3, r4], [r1, { range: r3, prefixText: "primary: " }, r4]); diff --git a/tests/cases/fourslash/renameDestructuringClassProperty.ts b/tests/cases/fourslash/renameDestructuringClassProperty.ts index 11261a4df78..ac708e55471 100644 --- a/tests/cases/fourslash/renameDestructuringClassProperty.ts +++ b/tests/cases/fourslash/renameDestructuringClassProperty.ts @@ -16,4 +16,7 @@ //// } ////} -verify.rangesAreRenameLocations(); +const [r0, r1, r2, r3, r4] = test.ranges(); +verify.renameLocations([r0, r2], [r0, { range: r1, suffixText: ": foo" }, r2, { range: r3, suffixText: ": foo" }]); +verify.renameLocations(r1, [{ range: r1, prefixText: "foo: " }]); +verify.renameLocations([r3, r4], [{ range: r3, prefixText: "foo: " }, r4]); diff --git a/tests/cases/fourslash/renameDestructuringDeclarationInFor.ts b/tests/cases/fourslash/renameDestructuringDeclarationInFor.ts index 0338433ae72..02bc0f50826 100644 --- a/tests/cases/fourslash/renameDestructuringDeclarationInFor.ts +++ b/tests/cases/fourslash/renameDestructuringDeclarationInFor.ts @@ -13,4 +13,6 @@ //// [|property1|] = p2; ////} -verify.rangesAreRenameLocations(); +const [r0, r1, r2, r3] = test.ranges(); +verify.renameLocations([r0, r1], [r0, r1, { range: r2, suffixText: ": property1" }]); +verify.renameLocations([r2, r3], [{ range: r2, prefixText: "property1: " }, r3]); diff --git a/tests/cases/fourslash/renameDestructuringDeclarationInForOf.ts b/tests/cases/fourslash/renameDestructuringDeclarationInForOf.ts index fcd55a5bc20..a8e21c83cf3 100644 --- a/tests/cases/fourslash/renameDestructuringDeclarationInForOf.ts +++ b/tests/cases/fourslash/renameDestructuringDeclarationInForOf.ts @@ -12,4 +12,6 @@ ////for (let { [|property1|]: p2 } of elems) { ////} -verify.rangesAreRenameLocations(); +const [r0, r1, r2, r3] = test.ranges(); +verify.renameLocations([r0, r3], [r0, { range: r1, suffixText: ": property1" }, r3]); +verify.renameLocations([r1, r2], [{ range: r1, prefixText: "property1: " }, r2]); diff --git a/tests/cases/fourslash/renameDestructuringFunctionParameter.ts b/tests/cases/fourslash/renameDestructuringFunctionParameter.ts index 4abbabc3723..d6a732176d2 100644 --- a/tests/cases/fourslash/renameDestructuringFunctionParameter.ts +++ b/tests/cases/fourslash/renameDestructuringFunctionParameter.ts @@ -4,4 +4,8 @@ //// f({[|a|]}); ////} -verify.rangesAreRenameLocations(); +const [r0, r1, r2] = test.ranges(); +// renames the local +verify.renameLocations([r0, r2], [{ range: r0, prefixText: "a: " }, { range: r2, prefixText: "a: " }]); +// renames the property +verify.renameLocations(r1, [{ range: r0, suffixText: ": a" }, r1, { range: r2, suffixText: ": a" }]); diff --git a/tests/cases/fourslash/renameDestructuringNestedBindingElement.ts b/tests/cases/fourslash/renameDestructuringNestedBindingElement.ts index 7557744ecee..6643382f6c9 100644 --- a/tests/cases/fourslash/renameDestructuringNestedBindingElement.ts +++ b/tests/cases/fourslash/renameDestructuringNestedBindingElement.ts @@ -15,4 +15,6 @@ //// console.log([|primary|]); ////} -verify.rangesAreRenameLocations(); +const [r0, r1, r2, r3] = test.ranges(); +verify.renameLocations([r0, r1], [r0, r1, { range: r2, suffixText: ": primary" }]); +verify.renameLocations([r2, r3], [{ range: r2, prefixText: "primary: " }, r3]); diff --git a/tests/cases/fourslash/renameImport.ts b/tests/cases/fourslash/renameImport.ts index 84d3ca3d335..6fdef347205 100644 --- a/tests/cases/fourslash/renameImport.ts +++ b/tests/cases/fourslash/renameImport.ts @@ -2,15 +2,32 @@ // @allowJs: true +// @Filename: /node_modules/global/index.d.ts +////export const x: number; + // @Filename: /a.ts ////export const x = 0; +// @Filename: /dir/index.ts +////export const x = 0; + // @Filename: /b.ts -////import * as a from "[|./a|]"; -////import a2 = require("[|./a"|]); +////import * as a from "./[|a|]"; +////import a2 = require("./[|a|]"); +////import * as dir from "./[|{| "target": "dir" |}dir|]"; +////import * as dir2 from "./dir/[|{| "target": "dir/index" |}index|]"; // @Filename: /c.js -////const a = require("[|./a|]"); +////const a = require("./[|a|]"); +////const global = require("/*global*/global"); verify.noErrors(); -goTo.eachRange(() => { verify.renameInfoFailed(); }); +goTo.eachRange(range => { + const target = range.marker && range.marker.data && range.marker.data.target; + const name = target === "dir" ? "/dir" : target === "dir/index" ? "/dir/index.ts" : "/a.ts"; + const kind = target === "dir" ? "directory" : "module"; + verify.renameInfoSucceeded(/*displayName*/ name, /*fullDisplayName*/ name, /*kind*/ kind, /*kindModifiers*/ "", /*fileToRename*/ name, range); +}); + +goTo.marker("global"); +verify.renameInfoFailed("You cannot rename a module via a global import."); diff --git a/tests/cases/fourslash/renameImportAndShorthand.ts b/tests/cases/fourslash/renameImportAndShorthand.ts index 4836d8c14fe..01be6650b3b 100644 --- a/tests/cases/fourslash/renameImportAndShorthand.ts +++ b/tests/cases/fourslash/renameImportAndShorthand.ts @@ -3,4 +3,5 @@ ////import [|foo|] from 'bar'; ////const bar = { [|foo|] }; -verify.rangesAreRenameLocations(); +const [r0, r1] = test.ranges(); +verify.renameLocations([r0, r1], [r0, { range: r1, prefixText: "foo: " }]); diff --git a/tests/cases/fourslash/renameImportNamespaceAndShorthand.ts b/tests/cases/fourslash/renameImportNamespaceAndShorthand.ts index 21cdc0fa820..e577d82d3ae 100644 --- a/tests/cases/fourslash/renameImportNamespaceAndShorthand.ts +++ b/tests/cases/fourslash/renameImportNamespaceAndShorthand.ts @@ -3,4 +3,5 @@ ////import * as [|foo|] from 'bar'; ////const bar = { [|foo|] }; -verify.rangesAreRenameLocations(); +const [r0, r1] = test.ranges(); +verify.renameLocations([r0, r1], [r0, { range: r1, prefixText: "foo: " }]); diff --git a/tests/cases/fourslash/renameImportRequire.ts b/tests/cases/fourslash/renameImportRequire.ts index 8a9aeebc328..bf29a0999b1 100644 --- a/tests/cases/fourslash/renameImportRequire.ts +++ b/tests/cases/fourslash/renameImportRequire.ts @@ -5,4 +5,6 @@ ////a = { [|e|] }; ////export { [|e|] }; -verify.rangesAreRenameLocations(); +const [r0, r1, r2, r3] = test.ranges(); +//TODO: export should have prefix/suffix too +verify.renameLocations([r0, r1, r2, r3], [r0, r1, { range: r2, prefixText: "e: " }, r3]); diff --git a/tests/cases/fourslash/renameParameterPropertyDeclaration4.ts b/tests/cases/fourslash/renameParameterPropertyDeclaration4.ts index ca201d28b2c..292c82a2d52 100644 --- a/tests/cases/fourslash/renameParameterPropertyDeclaration4.ts +++ b/tests/cases/fourslash/renameParameterPropertyDeclaration4.ts @@ -6,4 +6,5 @@ //// } //// } -verify.rangesAreRenameLocations(); +const [r0, r1] = test.ranges(); +verify.renameLocations([r0, r1], [{ range: r0, prefixText: "protectedParam: " }, r1]); diff --git a/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts b/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts index 1c499efc7e2..d915c55e320 100644 --- a/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts +++ b/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts @@ -15,6 +15,6 @@ //// a.fo/*2*/ verify.completions( - { marker: "1", includes: { name: "foo", text: "var foo: (p1: string) => void", documentation: "Modify the parameter" } }, - { marker: "2", exact: { name: "foo", text: "(property) a.foo: (p1: string) => void", documentation: "Modify the parameter" } }, + { marker: "1", includes: { name: "foo", text: "var foo: (p1: string) => void", documentation: "Modify the parameter", tags: [{ name: "param", text: "p1" }] } }, + { marker: "2", exact: { name: "foo", text: "(property) a.foo: (p1: string) => void", documentation: "Modify the parameter", tags: [{ name: "param", text: "p1" }] } }, ); diff --git a/tests/cases/fourslash/signatureHelpInAdjacentBlockBody.ts b/tests/cases/fourslash/signatureHelpInAdjacentBlockBody.ts new file mode 100644 index 00000000000..576f3a28b47 --- /dev/null +++ b/tests/cases/fourslash/signatureHelpInAdjacentBlockBody.ts @@ -0,0 +1,15 @@ +/// + +////declare function foo(...args); +//// +////foo(() => {/*1*/}/*2*/) + +goTo.marker("1"); +verify.signatureHelpPresentForTriggerReason({ + kind: "invoked", +}); + +goTo.marker("2"); +verify.signatureHelpPresentForTriggerReason({ + kind: "invoked", +}); \ No newline at end of file diff --git a/tests/cases/fourslash/tsxCompletion13.ts b/tests/cases/fourslash/tsxCompletion13.ts index 60964acbc55..9a79de927d2 100644 --- a/tests/cases/fourslash/tsxCompletion13.ts +++ b/tests/cases/fourslash/tsxCompletion13.ts @@ -2,7 +2,7 @@ //@Filename: file.tsx // @jsx: preserve -// @noLib: true +// @skipLibCheck: true //// declare module JSX { //// interface Element { } diff --git a/tests/cases/fourslash/tsxCompletionUnionElementType.ts b/tests/cases/fourslash/tsxCompletionUnionElementType.ts index 4a1044e20ac..5669f188f5b 100644 --- a/tests/cases/fourslash/tsxCompletionUnionElementType.ts +++ b/tests/cases/fourslash/tsxCompletionUnionElementType.ts @@ -2,7 +2,7 @@ //@Filename: file.tsx // @jsx: preserve -// @noLib: true +// @skipLibCheck: true //// declare module JSX { //// interface Element { } @@ -20,4 +20,4 @@ //// goTo.marker(); -verify.completionListContains("x", "(property) x: number | boolean"); \ No newline at end of file +verify.completionListIsEmpty(); \ No newline at end of file diff --git a/tests/cases/fourslash/tsxGoToDefinitionStatelessFunction2.ts b/tests/cases/fourslash/tsxGoToDefinitionStatelessFunction2.ts index a85c240e450..8541e3c391b 100644 --- a/tests/cases/fourslash/tsxGoToDefinitionStatelessFunction2.ts +++ b/tests/cases/fourslash/tsxGoToDefinitionStatelessFunction2.ts @@ -31,10 +31,10 @@ //// let opt = <[|Main/*sixthTarget*/Button|] wrong />; verify.goToDefinition({ - firstTarget: "thirdSource", - secondTarget: "thirdSource", + firstTarget: "firstSource", + secondTarget: "firstSource", thirdTarget: "firstSource", fourthTarget: "firstSource", fifthTarget: "secondSource", - sixthTarget: "thirdSource" + sixthTarget: "firstSource" }); diff --git a/tests/cases/fourslash/tsxGoToDefinitionUnionElementType1.ts b/tests/cases/fourslash/tsxGoToDefinitionUnionElementType1.ts index 957b6b811e0..9e4cb4e1b1b 100644 --- a/tests/cases/fourslash/tsxGoToDefinitionUnionElementType1.ts +++ b/tests/cases/fourslash/tsxGoToDefinitionUnionElementType1.ts @@ -22,5 +22,5 @@ //// <[|SFC/*one*/Comp|] x /> verify.goToDefinition({ - "one": ["def", "pt1"], + "one": ["def"], }); diff --git a/tests/cases/fourslash/tsxQuickInfo7.ts b/tests/cases/fourslash/tsxQuickInfo7.ts index 72de1128049..8b3493dd8d4 100644 --- a/tests/cases/fourslash/tsxQuickInfo7.ts +++ b/tests/cases/fourslash/tsxQuickInfo7.ts @@ -4,9 +4,9 @@ // @jsx: preserve // @noLib: true -//// declare function OverloadComponent(): JSX.Element; //// declare function OverloadComponent(attr: {b: U, a?: string, "ignore-prop": boolean}): JSX.Element; //// declare function OverloadComponent(attr: {b: U, a: T}): JSX.Element; +//// declare function OverloadComponent(): JSX.Element; // effective argument type of `{}`, needs to be last //// function Baz(arg1: T, arg2: U) { //// let a0 = ; @@ -22,7 +22,7 @@ verify.quickInfos({ 1: "function OverloadComponent(attr: {\n b: number;\n a?: string;\n \"ignore-prop\": boolean;\n}): any (+2 overloads)", 2: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)", 3: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)", - 4: "function OverloadComponent(attr: {\n b: number;\n a?: string;\n \"ignore-prop\": boolean;\n}): any (+2 overloads)", + 4: "function OverloadComponent(): any (+2 overloads)", // Subtype pass chooses this overload, since `a` is missing from the top overload, and `ignore-prop` is missing from the second (while T & {ignore-prop: true} is a proper subtype of `{}`) 5: "function OverloadComponent(): any (+2 overloads)", 6: "function OverloadComponent(attr: {\n b: string & number;\n a: boolean;\n}): any (+2 overloads)", 7: "function OverloadComponent(attr: {\n b: number & string;\n a: boolean;\n}): any (+2 overloads)", diff --git a/tests/cases/fourslash/unusedLocalsInFunction2.ts b/tests/cases/fourslash/unusedLocalsInFunction2.ts index 83816e68038..b0b0b69a2fa 100644 --- a/tests/cases/fourslash/unusedLocalsInFunction2.ts +++ b/tests/cases/fourslash/unusedLocalsInFunction2.ts @@ -6,4 +6,4 @@ //// x+1; ////} -verify.rangeAfterCodeFix("var x;"); +verify.rangeAfterCodeFix("var x;", undefined, undefined, 0); diff --git a/tests/lib/react16.d.ts b/tests/lib/react16.d.ts new file mode 100644 index 00000000000..4b91fb0c6fe --- /dev/null +++ b/tests/lib/react16.d.ts @@ -0,0 +1,2569 @@ +// Type definitions for React 16.4 +// Project: http://facebook.github.io/react/ +// Definitions by: Asana +// AssureSign +// Microsoft +// John Reilly +// Benoit Benezech +// Patricio Zavolinsky +// Digiguru +// Eric Anderson +// Albert Kurniawan +// Tanguy Krotoff +// Dovydas Navickas +// Stéphane Goetz +// Josh Rutherford +// Guilherme Hübner +// Ferdy Budhidharma +// Johann Rakotoharisoa +// Olivier Pascal +// Martin Hochel +// Frank Li +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +interface HTMLWebViewElement extends HTMLElement {} + +declare module "prop-types" { + // Type definitions for prop-types 15.5 + // Project: https://github.com/reactjs/prop-types + // Definitions by: DovydasNavickas + // Ferdy Budhidharma + // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + // TypeScript Version: 2.8 + + import { ReactNode, ReactElement } from 'react'; + + export const nominalTypeHack: unique symbol; + + export type IsOptional = undefined | null extends T ? true : undefined extends T ? true : null extends T ? true : false; + + export type RequiredKeys = { [K in keyof V]: V[K] extends Validator ? IsOptional extends true ? never : K : never }[keyof V]; + export type OptionalKeys = Exclude>; + export type InferPropsInner = { [K in keyof V]: InferType; }; + + export interface Validator { + (props: object, propName: string, componentName: string, location: string, propFullName: string): Error | null; + [nominalTypeHack]?: T; + } + + export interface Requireable extends Validator { + isRequired: Validator>; + } + + export type ValidationMap = { [K in keyof T]-?: Validator }; + + export type InferType = V extends Validator ? T : any; + export type InferProps = + & InferPropsInner>> + & Partial>>>; + + export const any: Requireable; + export const array: Requireable; + export const bool: Requireable; + export const func: Requireable<(...args: any[]) => any>; + export const number: Requireable; + export const object: Requireable; + export const string: Requireable; + export const node: Requireable; + export const element: Requireable>; + export const symbol: Requireable; + export function instanceOf(expectedClass: new (...args: any[]) => T): Requireable; + export function oneOf(types: T[]): Requireable; + export function oneOfType>(types: T[]): Requireable>>; + export function arrayOf(type: Validator): Requireable; + export function objectOf(type: Validator): Requireable<{ [K in keyof any]: T; }>; + export function shape

>(type: P): Requireable>; + export function exact

>(type: P): Requireable>>; + + /** + * Assert that the values match with the type specs. + * Error messages are memorized and will only be shown once. + * + * @param typeSpecs Map of name to a ReactPropType + * @param values Runtime values that need to be type-checked + * @param location e.g. "prop", "context", "child context" + * @param componentName Name of the component for error messages. + * @param getStack Returns the component stack. + */ + export function checkPropTypes(typeSpecs: any, values: any, location: string, componentName: string, getStack?: () => any): void; + +} + +declare module "react" { + + import * as PropTypes from 'prop-types'; + + type NativeAnimationEvent = AnimationEvent; + type NativeClipboardEvent = ClipboardEvent; + type NativeCompositionEvent = CompositionEvent; + type NativeDragEvent = DragEvent; + type NativeFocusEvent = FocusEvent; + type NativeKeyboardEvent = KeyboardEvent; + type NativeMouseEvent = MouseEvent; + type NativeTouchEvent = TouchEvent; + type NativePointerEvent = PointerEvent; + type NativeTransitionEvent = TransitionEvent; + type NativeUIEvent = UIEvent; + type NativeWheelEvent = WheelEvent; + + // tslint:disable-next-line:export-just-namespace + export = React; + + namespace React { + // + // React Elements + // ---------------------------------------------------------------------- + + type ReactType

= string | ComponentType

; + type ComponentType

= ComponentClass

| StatelessComponent

; + + type Key = string | number; + + interface RefObject { + readonly current: T | null; + } + + type Ref = string | { bivarianceHack(instance: T | null): any }["bivarianceHack"] | RefObject; + + type ComponentState = any; + + interface Attributes { + key?: Key; + } + interface ClassAttributes extends Attributes { + ref?: Ref; + } + + interface ReactElement

{ + type: string | ComponentClass

| SFC

; + props: P; + key: Key | null; + } + + interface SFCElement

extends ReactElement

{ + type: SFC

; + } + + type CElement> = ComponentElement; + interface ComponentElement> extends ReactElement

{ + type: ComponentClass

; + ref?: Ref; + } + + type ClassicElement

= CElement>; + + // string fallback for custom web-components + interface DOMElement

| SVGAttributes, T extends Element> extends ReactElement

{ + type: string; + ref: Ref; + } + + // ReactHTML for ReactHTMLElement + // tslint:disable-next-line:no-empty-interface + interface ReactHTMLElement extends DetailedReactHTMLElement, T> { } + + interface DetailedReactHTMLElement

, T extends HTMLElement> extends DOMElement { + type: keyof ReactHTML; + } + + // ReactSVG for ReactSVGElement + interface ReactSVGElement extends DOMElement, SVGElement> { + type: keyof ReactSVG; + } + + interface ReactPortal extends ReactElement { + key: Key | null; + children: ReactNode; + } + + // + // Factories + // ---------------------------------------------------------------------- + + type Factory

= (props?: Attributes & P, ...children: ReactNode[]) => ReactElement

; + + type SFCFactory

= (props?: Attributes & P, ...children: ReactNode[]) => SFCElement

; + + type ComponentFactory> = + (props?: ClassAttributes & P, ...children: ReactNode[]) => CElement; + + type CFactory> = ComponentFactory; + type ClassicFactory

= CFactory>; + + type DOMFactory

, T extends Element> = + (props?: ClassAttributes & P | null, ...children: ReactNode[]) => DOMElement; + + // tslint:disable-next-line:no-empty-interface + interface HTMLFactory extends DetailedHTMLFactory, T> { } + + interface DetailedHTMLFactory

, T extends HTMLElement> extends DOMFactory { + (props?: ClassAttributes & P | null, ...children: ReactNode[]): DetailedReactHTMLElement; + } + + interface SVGFactory extends DOMFactory, SVGElement> { + (props?: ClassAttributes & SVGAttributes | null, ...children: ReactNode[]): ReactSVGElement; + } + + // + // React Nodes + // http://facebook.github.io/react/docs/glossary.html + // ---------------------------------------------------------------------- + + type ReactText = string | number; + type ReactChild = ReactElement | ReactText; + + interface ReactNodeArray extends Array { } + type ReactFragment = {} | ReactNodeArray; + type ReactNode = ReactChild | ReactFragment | ReactPortal | string | number | boolean | null | undefined; + + // + // Top Level API + // ---------------------------------------------------------------------- + + // DOM Elements + function createFactory( + type: keyof ReactHTML): HTMLFactory; + function createFactory( + type: keyof ReactSVG): SVGFactory; + function createFactory

, T extends Element>( + type: string): DOMFactory; + + // Custom components + function createFactory

(type: SFC

): SFCFactory

; + function createFactory

( + type: ClassType, ClassicComponentClass

>): CFactory>; + function createFactory, C extends ComponentClass

>( + type: ClassType): CFactory; + function createFactory

(type: ComponentClass

): Factory

; + + // DOM Elements + // TODO: generalize this to everything in `keyof ReactHTML`, not just "input" + function createElement( + type: "input", + props?: InputHTMLAttributes & ClassAttributes | null, + ...children: ReactNode[]): DetailedReactHTMLElement, HTMLInputElement>; + function createElement

, T extends HTMLElement>( + type: keyof ReactHTML, + props?: ClassAttributes & P | null, + ...children: ReactNode[]): DetailedReactHTMLElement; + function createElement

, T extends SVGElement>( + type: keyof ReactSVG, + props?: ClassAttributes & P | null, + ...children: ReactNode[]): ReactSVGElement; + function createElement

, T extends Element>( + type: string, + props?: ClassAttributes & P | null, + ...children: ReactNode[]): DOMElement; + + // Custom components + function createElement

( + type: SFC

, + props?: Attributes & P | null, + ...children: ReactNode[]): SFCElement

; + function createElement

( + type: ClassType, ClassicComponentClass

>, + props?: ClassAttributes> & P | null, + ...children: ReactNode[]): CElement>; + function createElement, C extends ComponentClass

>( + type: ClassType, + props?: ClassAttributes & P | null, + ...children: ReactNode[]): CElement; + function createElement

( + type: SFC

| ComponentClass

| string, + props?: Attributes & P | null, + ...children: ReactNode[]): ReactElement

; + + // DOM Elements + // ReactHTMLElement + function cloneElement

, T extends HTMLElement>( + element: DetailedReactHTMLElement, + props?: P, + ...children: ReactNode[]): DetailedReactHTMLElement; + // ReactHTMLElement, less specific + function cloneElement

, T extends HTMLElement>( + element: ReactHTMLElement, + props?: P, + ...children: ReactNode[]): ReactHTMLElement; + // SVGElement + function cloneElement

, T extends SVGElement>( + element: ReactSVGElement, + props?: P, + ...children: ReactNode[]): ReactSVGElement; + // DOM Element (has to be the last, because type checking stops at first overload that fits) + function cloneElement

, T extends Element>( + element: DOMElement, + props?: DOMAttributes & P, + ...children: ReactNode[]): DOMElement; + + // Custom components + function cloneElement

( + element: SFCElement

, + props?: Partial

& Attributes, + ...children: ReactNode[]): SFCElement

; + function cloneElement>( + element: CElement, + props?: Partial

& ClassAttributes, + ...children: ReactNode[]): CElement; + function cloneElement

( + element: ReactElement

, + props?: Partial

& Attributes, + ...children: ReactNode[]): ReactElement

; + + // Context via RenderProps + interface ProviderProps { + value: T; + children?: ReactNode; + } + + interface ConsumerProps { + children: (value: T) => ReactNode; + unstable_observedBits?: number; + } + + type Provider = ComponentType>; + type Consumer = ComponentType>; + interface Context { + Provider: Provider; + Consumer: Consumer; + } + function createContext( + defaultValue: T, + calculateChangedBits?: (prev: T, next: T) => number + ): Context; + + function isValidElement

(object: {} | null | undefined): object is ReactElement

; + + const Children: ReactChildren; + const Fragment: ComponentType; + const StrictMode: ComponentType; + const version: string; + + // + // Component API + // ---------------------------------------------------------------------- + + type ReactInstance = Component | Element; + + // Base component for plain JS classes + // tslint:disable-next-line:no-empty-interface + interface Component

extends ComponentLifecycle { } + class Component { + constructor(props: Readonly

); + /** + * @deprecated + * https://reactjs.org/docs/legacy-context.html + */ + constructor(props: P, context?: any); + + // We MUST keep setState() as a unified signature because it allows proper checking of the method return type. + // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365#issuecomment-351013257 + // Also, the ` | S` allows intellisense to not be dumbisense + setState( + state: ((prevState: Readonly, props: Readonly

) => (Pick | S | null)) | (Pick | S | null), + callback?: () => void + ): void; + + forceUpdate(callBack?: () => void): void; + render(): ReactNode; + + // React.Props is now deprecated, which means that the `children` + // property is not available on `P` by default, even though you can + // always pass children as variadic arguments to `createElement`. + // In the future, if we can define its call signature conditionally + // on the existence of `children` in `P`, then we should remove this. + readonly props: Readonly<{ children?: ReactNode }> & Readonly

; + state: Readonly; + /** + * @deprecated + * https://reactjs.org/docs/legacy-context.html + */ + context: any; + /** + * @deprecated + * https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs + */ + refs: { + [key: string]: ReactInstance + }; + } + + class PureComponent

extends Component { } + + interface ClassicComponent

extends Component { + replaceState(nextState: S, callback?: () => void): void; + isMounted(): boolean; + getInitialState?(): S; + } + + interface ChildContextProvider { + getChildContext(): CC; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + type SFC

= StatelessComponent

; + interface StatelessComponent

{ + (props: P & { children?: ReactNode }, context?: any): ReactElement | null; + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + defaultProps?: Partial

; + displayName?: string; + } + + interface RefForwardingComponent { + (props: P & { children?: ReactNode }, ref?: Ref): ReactElement | null; + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + defaultProps?: Partial

; + displayName?: string; + } + + interface ComponentClass

extends StaticLifecycle { + new(props: P, context?: any): Component; + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap; + defaultProps?: Partial

; + displayName?: string; + } + + interface ClassicComponentClass

extends ComponentClass

{ + new(props: P, context?: any): ClassicComponent; + getDefaultProps?(): P; + } + + /** + * We use an intersection type to infer multiple type parameters from + * a single argument, which is useful for many top-level API defs. + * See https://github.com/Microsoft/TypeScript/issues/7234 for more info. + */ + type ClassType, C extends ComponentClass

> = + C & + (new (props: P, context?: any) => T) & + (new (props: P, context?: any) => { props: P }); + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + // This should actually be something like `Lifecycle | DeprecatedLifecycle`, + // as React will _not_ call the deprecated lifecycle methods if any of the new lifecycle + // methods are present. + interface ComponentLifecycle extends NewLifecycle, DeprecatedLifecycle { + /** + * Called immediately after a component is mounted. Setting state here will trigger re-rendering. + */ + componentDidMount?(): void; + /** + * Called to determine whether the change in props and state should trigger a re-render. + * + * `Component` always returns true. + * `PureComponent` implements a shallow comparison on props and state and returns true if any + * props or states have changed. + * + * If false is returned, `Component#render`, `componentWillUpdate` + * and `componentDidUpdate` will not be called. + */ + shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean; + /** + * Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as + * cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`. + */ + componentWillUnmount?(): void; + /** + * Catches exceptions generated in descendant components. Unhandled exceptions will cause + * the entire component tree to unmount. + */ + componentDidCatch?(error: Error, errorInfo: ErrorInfo): void; + } + + // Unfortunately, we have no way of declaring that the component constructor must implement this + interface StaticLifecycle { + getDerivedStateFromProps?: GetDerivedStateFromProps; + } + + type GetDerivedStateFromProps = + /** + * Returns an update to a component's state based on its new props and old state. + * + * Note: its presence prevents any of the deprecated lifecycle methods from being invoked + */ + (nextProps: Readonly

, prevState: S) => Partial | null; + + // This should be "infer SS" but can't use it yet + interface NewLifecycle { + /** + * Runs before React applies the result of `render` to the document, and + * returns an object to be given to componentDidUpdate. Useful for saving + * things such as scroll position before `render` causes changes to it. + * + * Note: the presence of getSnapshotBeforeUpdate prevents any of the deprecated + * lifecycle events from running. + */ + getSnapshotBeforeUpdate?(prevProps: Readonly

, prevState: Readonly): SS | null; + /** + * Called immediately after updating occurs. Not called for the initial render. + * + * The snapshot is only present if getSnapshotBeforeUpdate is present and returns non-null. + */ + componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, snapshot?: SS): void; + } + + interface DeprecatedLifecycle { + /** + * Called immediately before mounting occurs, and before `Component#render`. + * Avoid introducing any side-effects or subscriptions in this method. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use componentDidMount or the constructor instead; will stop working in React 17 + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + componentWillMount?(): void; + /** + * Called immediately before mounting occurs, and before `Component#render`. + * Avoid introducing any side-effects or subscriptions in this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use componentDidMount or the constructor instead + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + UNSAFE_componentWillMount?(): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling `Component#setState` generally does not trigger this method. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use static getDerivedStateFromProps instead; will stop working in React 17 + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling `Component#setState` generally does not trigger this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use static getDerivedStateFromProps instead + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + UNSAFE_componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call `Component#setState` here. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17 + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call `Component#setState` here. + * + * This method will not stop working in React 17. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + UNSAFE_componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + } + + interface Mixin extends ComponentLifecycle { + mixins?: Array>; + statics?: { + [key: string]: any; + }; + + displayName?: string; + propTypes?: ValidationMap; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap; + + getDefaultProps?(): P; + getInitialState?(): S; + } + + interface ComponentSpec extends Mixin { + render(): ReactNode; + + [propertyName: string]: any; + } + + function createRef(): RefObject; + + function forwardRef(Component: RefForwardingComponent): ComponentType

>; + + // + // Event System + // ---------------------------------------------------------------------- + + interface SyntheticEvent { + bubbles: boolean; + /** + * A reference to the element on which the event listener is registered. + */ + currentTarget: EventTarget & T; + cancelable: boolean; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + nativeEvent: Event; + preventDefault(): void; + isDefaultPrevented(): boolean; + stopPropagation(): void; + isPropagationStopped(): boolean; + persist(): void; + // If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239 + /** + * A reference to the element from which the event was originally dispatched. + * This might be a child element to the element on which the event listener is registered. + * + * @see currentTarget + */ + target: EventTarget; + timeStamp: number; + type: string; + } + + interface ClipboardEvent extends SyntheticEvent { + clipboardData: DataTransfer; + nativeEvent: NativeClipboardEvent; + } + + interface CompositionEvent extends SyntheticEvent { + data: string; + nativeEvent: NativeCompositionEvent; + } + + interface DragEvent extends MouseEvent { + dataTransfer: DataTransfer; + nativeEvent: NativeDragEvent; + } + + interface PointerEvent extends MouseEvent { + pointerId: number; + pressure: number; + tiltX: number; + tiltY: number; + width: number; + height: number; + pointerType: 'mouse' | 'pen' | 'touch'; + isPrimary: boolean; + nativeEvent: NativePointerEvent; + } + + interface FocusEvent extends SyntheticEvent { + nativeEvent: NativeFocusEvent; + relatedTarget: EventTarget; + target: EventTarget & T; + } + + // tslint:disable-next-line:no-empty-interface + interface FormEvent extends SyntheticEvent { + } + + interface InvalidEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface ChangeEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface KeyboardEvent extends SyntheticEvent { + altKey: boolean; + charCode: number; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: string): boolean; + /** + * See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values + */ + key: string; + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + nativeEvent: NativeKeyboardEvent; + repeat: boolean; + shiftKey: boolean; + which: number; + } + + interface MouseEvent extends SyntheticEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: string): boolean; + metaKey: boolean; + nativeEvent: NativeMouseEvent; + pageX: number; + pageY: number; + relatedTarget: EventTarget; + screenX: number; + screenY: number; + shiftKey: boolean; + } + + interface TouchEvent extends SyntheticEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: string): boolean; + metaKey: boolean; + nativeEvent: NativeTouchEvent; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + interface UIEvent extends SyntheticEvent { + detail: number; + nativeEvent: NativeUIEvent; + view: AbstractView; + } + + interface WheelEvent extends MouseEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + nativeEvent: NativeWheelEvent; + } + + interface AnimationEvent extends SyntheticEvent { + animationName: string; + elapsedTime: number; + nativeEvent: NativeAnimationEvent; + pseudoElement: string; + } + + interface TransitionEvent extends SyntheticEvent { + elapsedTime: number; + nativeEvent: NativeTransitionEvent; + propertyName: string; + pseudoElement: string; + } + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + type EventHandler> = { bivarianceHack(event: E): void }["bivarianceHack"]; + + type ReactEventHandler = EventHandler>; + + type ClipboardEventHandler = EventHandler>; + type CompositionEventHandler = EventHandler>; + type DragEventHandler = EventHandler>; + type FocusEventHandler = EventHandler>; + type FormEventHandler = EventHandler>; + type ChangeEventHandler = EventHandler>; + type KeyboardEventHandler = EventHandler>; + type MouseEventHandler = EventHandler>; + type TouchEventHandler = EventHandler>; + type PointerEventHandler = EventHandler>; + type UIEventHandler = EventHandler>; + type WheelEventHandler = EventHandler>; + type AnimationEventHandler = EventHandler>; + type TransitionEventHandler = EventHandler>; + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + /** + * @deprecated. This was used to allow clients to pass `ref` and `key` + * to `createElement`, which is no longer necessary due to intersection + * types. If you need to declare a props object before passing it to + * `createElement` or a factory, use `ClassAttributes`: + * + * ```ts + * var b: Button | null; + * var props: ButtonProps & ClassAttributes